“Error: Could not find or load main class My.class”

我们两清 提交于 2019-12-30 03:29:06

问题


Im using Java SDK 1.7 on Windows 7 via cmd.exe . Up until a few hours ago everything was working correctly when suddenly I was unable to run my compiled class files, consistently presented with the error in the title.

I seem to be able to compile my My.java file however I am unable to run the resulting class file (My.class). I am constantly given the error "Error: Could not find or load main class My.class". I have tried this with multiple other class files all resulting in the same problem.

My 'Path' environment variable is set to "C:\Program Files (x86)\Java\jdk1.7.0_05\bin" if you were wondering

I have tried reinstalling, creating and setting a classpath variable (no luck), and even directly using the

java -cp . My.class

command.

I have tried these posts all to no avail, hence why I'm posting:

Error: Could not find or load main class

Error: Could not find or load main class- Novice

Could not find or load main class

Java 1.7.0_03 Error: Could not find or load main class

If it makes any difference my code is :

import javax.swing.JOptionPane;

class My {
    public static void main(String[] args) {
       final double x = 3.2;
       int i = (int)x;
       double m = 0;
       if (x < 4) {
          String saySomething = JOptionPane.showInputDialog(i);
          System.out.println(saySomething);
        }
       else {
          String saySomething = JOptionPane.showInputDialog(i);
          System.out.println("Hello World");
        }
       while (m < 10) {
            System.out.print(" While Loop ");
            m++;
        };
       for (i=1; i < 10; i++) {
           System.out.println("For Loop");
        };

    }
}

回答1:


You should specify the classname instead of the file of the class to load. The difference is a simple matter of removing the .class extension.




回答2:


I would use an IDE and you shouldn't get these issues. Compile and run is just a click of the mouse.

BTW to run your program from the command line

java -cp . My

You don't add .class




回答3:


Position yourself in a directory of your project (you need to have src and bin directories there, assuming you keep sources in src and binaries in bin)

java -cp bin My



回答4:


I myself was facing the same problem. It was happening because I was being remiss in typing the name of the class properly. In my instance, I was typing

java doubler

instead of

java Doubler



来源:https://stackoverflow.com/questions/11473854/error-could-not-find-or-load-main-class-my-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!