java - 创建对象时如何修复 "Error: Cannot find symbol"?

标签 java class inheritance methods

我不明白我的编译器如何找不到类 Weight,考虑到我不是已经在我的 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 类。

关于java - 创建对象时如何修复 "Error: Cannot find symbol"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55370592/

相关文章:

java - 在 Java 中,类 B<T> 扩展 A<T> 和类 B<T> 扩展 A 之间有什么区别

C#:WCF:接口(interface)继承和转换问题

Java线程监控。如何找出非守护程序 Activity 线程?

Java正则表达式替换除少数字符组合之外的所有字符

将指针转换为 cython 中类的实例

c++ - 在作为此类实例的类中创建公共(public)属性

c++ - 在类中获取 "this"的上下文并分配给类指针 TheClass*

java - 我可以创建一个类作为每种 Activity 类型的父类吗?

java - 带有对象引用的 JPA 复合键

java - spring-security.xml 中的密码更改