线程“main”中的异常 java.lang.NoClassDefFoundError

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2506749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:32:41  来源:igfitidea点击:

Exception in thread "main" java.lang.NoClassDefFoundError

java

提问by Manu

package pack;


public class sample{ 

 public static void main(String input[])
    {

        NumberFormat numberFormat = new DecimalFormat("#,##0.00##");
    System.out.println(numberFormat.format(44533125.00));

    } 
}

the code is working fine in the current dir.. (c:/myprogram/).

代码在当前目录中运行良好.. (c:/myprogram/)。

after that i copy the sample.class file and paste it in other dir(d:/myprogram). i got error while running, like

之后,我复制了 sample.class 文件并将其粘贴到其他目录(d:/myprogram)中。我在运行时出错,比如

Exception in thread "main" java.lang.NoClassDefFoundError: sample (wrong name: pack/sample)

In java .class file can run anywhere right? but why i am not able to run?

java中的.class文件可以在任何地方运行吗?但为什么我不能跑?

回答by Jon Skeet

You should have the class file within the package - so it should be in a directory called pack. Then with the parent directory in the classpath, you'd run

您应该在包中包含类文件 - 因此它应该位于名为pack. 然后使用类路径中的父目录,您将运行

java pack.sample

(You should also change the class name to Sample to follow conventions, btw - and run pack.Sample.)

(您还应该将类名更改为 Sample 以遵循约定,顺便说一句 - 并运行pack.Sample。)

If you're building with javac, specify the "-d" option to tell it the base directory, and it will create the appropriate package structure if necessary. For example:

如果您使用 javac 构建,请指定“-d”选项来告诉它基本目录,如果需要,它将创建适当的包结构。例如:

javac -d classes Sample.java

or

或者

javac -d classes src/pack/Sample.java

will (in both cases) create

将(在这两种情况下)创建

classes/pack/Sample.class

You could then run

然后你可以运行

java -cp classes pack.Sample

回答by Huupke

IntelliJ and maybe other IDE's do not refactor your Run/Debug configuration. You must manually change your package name preceding the name of your Main class. For instance, change 'sample.Main' to 'com.company.package.ui.Main' so it will launch correctly next time you try to run it. The IDE might have already marked the Run/Debug button with a red cross because it couldn't find the main class. It also gives a warning when you open the Run/Debug configuration.

IntelliJ 和其他 IDE 可能不会重构您的运行/调试配置。您必须在 Main 类名称之前手动更改包名称。例如,将 'sample.Main' 更改为 'com.company.package.ui.Main' 以便下次尝试运行它时它会正确启动。IDE 可能已经用红叉标记了运行/调试按钮,因为它找不到主类。当您打开运行/调试配置时,它还会发出警告。

回答by Rudolf

If you are not using a single java/class file you can also remove the package statement.

如果您不使用单个 java/class 文件,您还可以删除 package 语句。