开发者

Exception in thread "main" java.lang.NoClassDefFoundError

开发者 https://www.devze.com 2022-12-24 16:48 出处:网络
package pack; public class sample{ public static void main(String input[]) { NumberFormat numberFormat = new DecimalFormat(\"#,##0.00##\");
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/).

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

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

I开发者_如何学JAVAn java .class file can run anywhere right? 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. 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.)

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 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. 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号