是否可以通过构造函数在方法中发送我需要的变量?
我有 2 个文件:
public class Recording {
public int height;
public int diameter;
public int weight;
public Recording (int height, int diameter, int weight) {
this.height = height;
this.diameter = diameter;
this.weight = weight;
}
}
和
public class Leergut {
public static void main(String[] args) {
int height;
int diameter;
int weight;
int code;
int pfand;
while (code != -1) {
Recording r = new Recording(System.in.read(), System.in.read(), System.in.read());
classify(r);
} else {
// to be continued
}
}
public static int classify(Recording r) {
if (height == 250 && diameter = 67 && weight == 365) { code = 0; return code;}
else { code = -1; return code ;}
}
我正在寻找一种方法将高度,直径和重量(如记录类中所述(传递给"分类"方法。
还是我需要再次声明方法中的变量,以使其工作?
PS:对于那些在我的第一个线程中试图帮助我的人,我决定写一篇新帖子,因为它会提供更好的概述。
您可以在"记录"中为高度、直径和宽度变量创建 getter 和 setter 方法。然后,在分类方法中调用它们。
例:
// Methods in Recording.java
public int getWidth() {
return this.width;
}
public int getDiameter()
return this.diameter;
}
public int getHeight() {
return this.height;
}
在分类方法中,只需从"记录"中获取值:
public static int classify(Recording r) {
if(r.getHeight() == 250 && r.getDiameter() == 67 && r.getWidth() == 365) {
// Do whatever
}
}
建议
您必须初始化变量,然后创建 3 个返回相应值的方法
public class Recording {
private int height = 0;
private int diameter = 0;
private int weight = 0;
public Recording (int height, int diameter, int weight) {
this.height = height;
this.diameter = diameter;
this.weight = weight;
}
public int getHeight()
{
return height;
}
public int getDiameter()
{
return diameter;
}
public int getWeight()
{
return weight;
}
}
public static int classify(Recording r) {
if (r.getHeight() == 250 && r.getDiameter() == 67 && r.getWeight() == 365) { code = 0; return code;}
else { code = -1; return code ;}
}
你的意思是这个?
public static int classify(Recording r) {
if (r.height == 250 && r.diameter = 67 && r.weight == 365) {
code = 0; return code;
}
else {
code = -1; return code ;
}
您的录制类及其字段是公共的,这意味着您只需调用它们的名称、点和您想要获取的字段即可访问它们。
为了将变量传递给方法,您可以这样做:
public void myMethod(int variable1, boolean variable2) {
//method body
}
你可以这样称呼它:
public static void main(String[] args){
int a = 2;
boolean f = false;
myMethod(a,f);
// If static do:
// ClassThatHasTheStaticMethod.myMethod(a,f);
}
作为旁注:
while (code != -1) {
Recording r = new Recording(System.in.read(), System.in.read(), System.in.read());
classify(r);
} else {
// to be continued
}
您不能在 while 代码块后面放置 else 语句,因为它会导致编译错误。
尝试了一种新的方法。再次声明方法中的变量(无法弄清楚如何使用"System.in.read(("调用 Setter 函数
public static int classify(Recording r) {
int height = System.in.read();
int diameter = System.in.read();
int weight = System.in.read();
if (height == 250 && diameter == 67 && weight == 365) {int code = 0; return code;}
else { int code = -1; return code ;}
}
但是,现在我的对象"记录r"告诉我无法再解析变量和系统读取((;对于方法中的 3 个变量,抛出某种 IOException。