Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Error: Could not find or load main class My.class"

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");
        };

    }
}
like image 526
James Milner Avatar asked Jul 13 '12 15:07

James Milner


3 Answers

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.

like image 193
user268396 Avatar answered Nov 08 '22 02:11

user268396


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

like image 38
Peter Lawrey Avatar answered Nov 08 '22 02:11

Peter Lawrey


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
like image 21
ioreskovic Avatar answered Nov 08 '22 01:11

ioreskovic