一旦您编写了一个Java程序,您需要使用javac命令来编译它,这将显示发生的编译时错误(如果有的话)。
一旦解析它们并成功编译程序,将在当前文件夹中生成一个与类名同名的可执行文件,扩展名为.class。
然后需要使用java命令执行它,如:
java class_name
在执行时,当JVM找不到具有指定名称的.class文件时,会出现运行时错误,错误为”Could not found or load main class”,即找不到或加载主类:
D:sample>java Example
Error: Could not find or load main class Example
Caused by: java.lang.ClassNotFoundException: Example
解决方案
要避免此错误因文件格式或文件扩展名无效打不开,需要指定当前目录中.class文件的绝对(包括包)名称(仅为名称)。
以下是可能发生此错误的情况:
1. 错误的类名—您可能指定了错误的类名。
class Example {
public static void main(String args[]){
System.out.println("This is an example class");
}
}
错误:
D:>javac Example.java
D:>java Exmple
Error: Could not find or load main class Exmple
Caused by: java.lang.ClassNotFoundException: Exmple
解决方案-在这个类名拼写错误,我们需要纠正它。
D:>javac Example.java
D:>java Example
This is an example class
2. 大小写错误-需要指定大小写相同的类的名称Example.java不同于example.java.
class Example {
public static void main(String args[]){
System.out.println("This is an example class");
}
}
错误:
D:>java EXAMPLE
Error: Could not find or load main class EXAMPLE
Caused by: java.lang.NoClassDefFoundError: Example (wrong name: EXAMPLE)
解决方案-在这种情况下因文件格式或文件扩展名无效打不开,类名是错误的,它应该被修饰。
D:>javac Example.java
D:>java Example
This is an example class
3. 错误的包—您可能在包中创建了.class文件,并尝试在没有包名称或包名称错误的情况下执行。
package sample;
class Example {
public static void main(String args[]){
System.out.println("This is an example class");
}
}
错误:
D:>javac -d . Example.java
D:>java samp.Example
Error: Could not find or load main class samp.Example
Caused by: java.lang.ClassNotFoundException: samp.Example
解决方案—在这个场景中,我们在执行时提到了错误的包名,我们需要指定正确的包名,其中.class文件作为
D:>javac -d . Example.java
D:>java sample.Example
This is an example class
包含.class扩展名—在执行文件时,无需在程序中包含.class扩展名,只需指定类文件的名称。
错误:
D:sample>java Example.class
Error: Could not find or load main class Example.class
Caused by: java.lang.ClassNotFoundException: Example.class
解决方案−执行程序时不需要extension.class
D:sample>java Example
This is an example class
Could Not Found Or Load Main Class
———END———
限 时 特 惠: 本站每日持续更新海量各大内部创业教程,一年会员只需98元,全站资源免费下载 点击网站首页每天更新
站 长 微 信: aiwo51889
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。