简体   繁体   English

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

[英]Exception in thread “main” java.lang.NoClassDefFoundError

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). 之后,我复制sample.class文件并将其粘贴到其他目录(d:/ myprogram)。 i got error while running, like 我跑步时遇到错误,比如

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

In java .class file can run anywhere right? 在java .class文件可以在任何地方运行吗? but why i am not able to run? 但为什么我不能跑?

You should have the class file within the package - so it should be in a directory called pack . 您应该在包中包含类文件 - 因此它应该位于名为pack的目录中。 Then with the parent directory in the classpath, you'd run 然后使用类路径中的父目录,运行

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. 如果您使用javac构建,请指定“-d”选项以告知它基本目录,并在必要时创建适当的包结构。 For example: 例如:

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

IntelliJ and maybe other IDE's do not refactor your Run/Debug configuration. IntelliJ和其他IDE可能不会重构您的运行/调试配置。 You must manually change your package name preceding the name of your Main class. 您必须手动更改Main类名称前面的包名称。 For instance, change 'sample.Main' to 'com.company.package.ui.Main' so it will launch correctly next time you try to run it. 例如,将'sample.Main'更改为'com.company.package.ui.Main',以便下次尝试运行时它将正确启动。 The IDE might have already marked the Run/Debug button with a red cross because it couldn't find the main class. IDE可能已经使用红叉标记了“运行/调试”按钮,因为它无法找到主类。 It also gives a warning when you open the Run/Debug configuration. 当您打开运行/调试配置时,它也会发出警告。

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

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

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