错误 class 未找到已修复,但我不明白为什么

Error class not Found fixed but I don't understand why

文件 "HelloDemo.java" 路径为“/test/hello/HelloDemo.java”

package test.hello;

public class HelloDemo {
  public static void main(String[] args) {
      System.out.print("Hello!!");
  }
}

当我"run"它时,发生错误。

Building HelloDemo.java and running HelloDemo
Error: Could not find or load main class HelloDemo

然后,我更改了代码。

//package test.hello;

public class HelloDemo {
  public static void main(String[] args) {
      System.out.print("Hello!!");
  }
}

当我"Run"它时,代码成功输出。

Building HelloDemo.java and running HelloDemo
Hello!!

这是关于"Run"的screenshot。 我修复了一个错误,但我不知道为什么,我需要帮助,谢谢!

如果我想保留包取消注释,如何解决?

使用您的 IDE 创建一个程序包并将您的 class 添加到其中。包名称将自动附加到顶部。 不管IDE,文件夹结构应该匹配包结构,你的问题可能出在这里。

那是因为您可能已经在 运行 之后更改了文件的位置。因此,运行 配置应该更改为在构建的 jar 中寻找新的 test.hello.HelloDemo class 而不是 HelloDemo(最初可能在默认包中)。你的 IDE 是多少?

备注:这不是因为你改变了文件的位置导致class路径改变,反之亦然。

在 IntelliJ 上,您应该这样做:https://www.jetbrains.com/help/idea/creating-and-editing-run-debug-configurations.html

一个class的名字其实就是包加上class的名字。在第一种情况下,您不能 运行 HelloDemo,因为那不是 class 名称。 class 名字是 test.hello.HelloDemo

通过注释掉包,您实际上已经将 class 重命名为 HelloDemo,因此它 运行s.

此外,当运行将class与main连接时,您必须在正确的位置。例如,如果 class 是 test.hello.HelloDemo,您的文件夹结构将是 /test/hello/HelloDemo.java

你必须在 / 和 运行 test.hello.HelloDemo 从那里。