AccountTest.java:10: error: cannot find symbol

AccountTest.java:10: error: cannot find symbol

我目前正在学习 java 并且我正在尝试我教科书中的一个例子,但我无法让它发挥作用。我不断收到“找不到符号”错误。 这是 class 帐户中的代码:

package account;

public class Account {

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

}

这是用于 AccountTest 的:

package account;

import java.util.Scanner;

public class AccountTest {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Account myAccount;
        myAccount = new Account();
        System.out.printf("initial name is %s%n%n", myAccount.getName());

        System.out.println("Please enter the name:");
        String theName = input.nextLine();
        myAccount.setName(theName);
        System.out.println();
        System.out.printf("name in object myAccount is: %n%s%n", myAccount.getName());
    }
}

我收到的错误信息是:

javac AccountTest.java
AccountTest.java:10: error: cannot find symbol
            Account myAccount;
            ^
  symbol:   class Account
  location: class AccountTest
AccountTest.java:11: error: cannot find symbol
            myAccount = new Account();
                            ^
  symbol:   class Account
  location: class AccountTest
2 errors

抱歉新手问题,感谢您的帮助!

您的代码工作正常。当您使用 IDE - 它正常工作。但是当你从控制台像这样编译它时:

cd account <-- move to your package with Account and AccountTest classes
javac AccountTest.java

您即将重新收到此问题。原因是 javac 没有自动包含所有导入的文件或当前目录中的文件(这个 IDE 包含)。所以你所要做的就是告诉javac所有要编译的文件。

javac AccountTest.java Account.java

因此,您将在文件夹中看到 AccountTest.classAccount.class 个文件。

最后 到 运行 您应该从控制台执行的代码:

java -classpath . AccountTest

P.S.看这个相关的回答How do I run a Java program from the command line on Windows?

I have already done that, when i tried to do javac Account.java it didn't give me an error code.

从命令行编译时需要同时指定类。

javac -cp . account/*.java

然后

java -cp . account.AccountTest

到运行吧。