[英]How to fix “Error: Cannot find symbol” when creating an object?
我不明白我的编译器如何找不到类Weight
,考虑到我是否已经在我的public boolean checkWeight
方法中public boolean checkWeight
? 编译器指向以下行:
`Weight first = new Weight();`
和
`Weight second = new Weight();`
public class Guard {
int stashWeight;
public Guard ( int maxWeight ) {
this.stashWeight = maxWeight;
}
public boolean checkWeight (Weight maxWeight) {
if ( maxWeight.weight >= stashWeight ) {
return true;
} else {
return false;
}
}
public static void main (String[] args ) {
Weight first = new Weight();
first.weight = 3000;
Weight second = new Weight();
second.weight = 120;
Guard grams = new Guard(450);
System.out.println("Officer, can I come in?");
boolean canFirstManGo = grams.checkWeight(first);
System.out.println(canFirstManGo);
System.out.println();
System.out.println("Officer, how about me?");
boolean canSecondManGo = grams.checkWeight(second);
System.out.println(canSecondManGo);
}
}
您应该这样定义Weight
类:
public class Weight {
public int weight;
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
输出:
Officer, can I come in?
true
Officer, how about me?
false
或使用import
关键字导入您的Weight
类。
您的代码中缺少您的Weight类请参见以下代码
class Weight {
public int weight;
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
public class Guard {
int stashWeight;
public Guard(int maxWeight) {
this.stashWeight = maxWeight;
}
public boolean checkWeight(Weight maxWeight) {
if (maxWeight.weight >= stashWeight) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Weight first = new Weight();
first.weight = 3000;
Weight second = new Weight();
second.weight = 120;
Guard grams = new Guard(450);
System.out.println("Officer, can I come in?");
boolean canFirstManGo = grams.checkWeight(first);
System.out.println(canFirstManGo);
System.out.println();
System.out.println("Officer, how about me?");
boolean canSecondManGo = grams.checkWeight(second);
System.out.println(canSecondManGo);
}
}
输出
**
Officer, can I come in?
true
Officer, how about me?
false
**
您的公共方法可能只是:
public boolean checkWeight(int maxWeight) {
return maxWeight >= stashWeight;
}
并且主要方法可以更新为:
public static void main(String[] args) {
int firstWeight = 3000;
int secondWeight = 120;
Guard grams = new Guard(450);
System.out.println("Officer, can I come in?");
boolean canFirstManGo = grams.checkWeight(firstWeight);
System.out.println(canFirstManGo);
System.out.println();
System.out.println("Officer, how about me?");
boolean canSecondManGo = grams.checkWeight(secondWeight);
System.out.println(canSecondManGo);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.