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

16,902

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

Solution 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

Solution 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
Share:
16,902
James Milner
Author by

James Milner

Updated on June 25, 2022

Comments

  • James Milner
    James Milner almost 2 years

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