找不到符号... - Java

Cannot find symbol... - Java

我是 OOP 概念的新手,我收到错误消息:找不到符号。同样在编译期间,我得到 2 个错误:

Error:(9, 35) java: <identifier> expected
Error:(9, 36) java: illegal start of type

如有任何帮助,我们将不胜感激。 这是我的两个 类:

package com.company;

public class Main {

    public static void main(String[] args) {

    }

    TestClass waterBottle = new waterBottle();
    waterBottle.bottleFill(5);
}

package com.company;

public class TestClass {

    TestClass() { }

    public void waterBottleFill(int y) {
        int bottleFill = y;
        System.out.println("Fill level is at:" + bottleFill);
    }

    public void waterBottleRefill(int x) {
        int refill = x;
    }
}

您的代码

TestClass waterBottle = new TestClass();
waterBottle.bottleFill(5);

实际上位于 class 定义中。

将此代码移至您的 main 方法:

public class Main {

    public static void main(String[] args) {
        TestClass waterBottle = new waterBottle();
        waterBottle.bottleFill(5);
    }
}

当您正确地格式化您的代码时,这个问题会变得明显和明显 - 使用标识、垂直和水平间距。我已经编辑了您的问题,因此现在格式正确。看看它现在的可读性如何。

另一个问题是您的 class 对象创建。您在 new waterBottle() 行提供的名称不正确。 new 后应跟一个正确的 class 名称:

TestClass waterBottle = new TestClass();
package com.company;

public class Main {

public static void main(String[] args) {


    //TestClass waterBottle = new waterBottle(); // what is waterbottle.. this will give you can not find symbol`
    TestClass waterBottle = new TestClass();//should be this


        waterBottle.bottleFill(5);
}// main method ends

}// class ends




package com.company;

public class TestClass {

TestClass(){}

public void waterBottleFill(int y){
    int bottleFill = y;
    System.out.println("Fill level is at:"+ bottleFill);

}
public void waterBottleRefill(int x){
    int refill = x;
}


}