简体   繁体   English

错误Java执行:找不到或加载主类

[英]Error java executing: Couldn't find or load the main class

I'm trying to execute a simple java code (I have already compiled it with no problems) but it gives me the next error: 我正在尝试执行一个简单的Java代码(我已经毫无问题地对其进行了编译),但是它给了我下一个错误:

c:\\Users\\alejandro\\Desktop> java HelloWorld.java Error: Couldn't find or load the main class. c:\\ Users \\ alejandro \\ Desktop> java HelloWorld.java错误:无法找到或加载主类。

The code is the next: 代码如下:

public class HelloWorld{

    public static void main(String[] args){

        System.out.println("Hello world!");

     }
}
  • I have set the PATH variable correctly. 我已经正确设置了PATH变量。
  • I have deleted CLASSPATH variable. 我已删除CLASSPATH变量。
  • I have both files (.java and .class) in my Desktop. 我的桌面上同时有两个文件(.java和.class)。

You're specifying the name of the source file . 您正在指定源文件的名称。 That's not what you provide to the java command - you specify the class name . 这不是您提供给java命令的内容-您指定了类名

java HelloWorld

This assumes that HelloWorld.class is somewhere on the classpath, which would default to "the current directory". 假定HelloWorld.class位于类路径上的某个位置,该位置默认为“当前目录”。

If you had a package, eg 如果您有包裹,例如

package foo;

public class HelloWorld {
    ...
}

Then you would want to put HelloWorld.java in a directory called foo , and compile and run from the root directory: 然后,您需要将HelloWorld.java放在名为foo的目录中,并从根目录编译并运行:

> javac foo\HelloWorld.java
> java foo.HelloWorld

Note how now the fully-qualified class name is foo.HelloWorld , not foo\\HelloWorld . 请注意,现在完全合格的类名称是foo.HelloWorld而不是foo\\HelloWorld

when you run the compiled file, you should use only the class name. 运行编译文件时,应仅使用类名。 The compiled file will have an extension of .class but you should not add any extension. 编译后的文件将具有.class扩展名,但您不应添加任何扩展名。 Just use the class name. 只需使用类名即可。

change 更改

c:\Users\alejandro\Desktop> java HelloWorld.java

to

c:\Users\alejandro\Desktop> java HelloWorld

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM