0

The file "HelloDemo.java" path is "/test/hello/HelloDemo.java"

package test.hello;

public class HelloDemo {
  public static void main(String[] args) {
      System.out.print("Hello!!");
  }
}

when I "run" it, an error occurred.

Building HelloDemo.java and running HelloDemo
Error: Could not find or load main class HelloDemo

Then, I changed the code.

//package test.hello;

public class HelloDemo {
  public static void main(String[] args) {
      System.out.print("Hello!!");
  }
}

when I "Run" it, code success output.

Building HelloDemo.java and running HelloDemo
Hello!!

This is the screenshot about the "Run". I fixed an error, but I don't konw why, I need help, Thank you!

If I want to keep the package uncomment, How to fix it?

Q.Super
  • 13
  • 2

3 Answers3

0

Create a package using your IDE and add your class to it. Package name will be appended to top automatically. Reguardless of IDE, folder structure should match package structure, your problem could be here.

Killer Death
  • 459
  • 2
  • 10
0

That's because you probably changed the location of your file after running it once already. Hence, the running configuration should change to look for the new test.hello.HelloDemo class inside the built jar and not for HelloDemo anymore (which was probably in the default package, initially). What is your IDE?

Remark: This is not because you changed the location of your file that the classpath changed, and vice-versa.

On IntelliJ, you should do this: https://www.jetbrains.com/help/idea/creating-and-editing-run-debug-configurations.html

belka
  • 1,480
  • 1
  • 18
  • 31
  • My IDE is ide.cloud9.io – Q.Super Aug 29 '17 at 14:11
  • Check this link: https://docs.c9.io/docs/running-and-debugging-code And modify the running configuration to set the correct class. If you put "package X.Y" inside the file, then your classpath is X.Y.ClassName – belka Aug 29 '17 at 14:12
  • Please mark the question as answered if as this answers your question. – belka Aug 29 '17 at 15:05
  • If I want to keep the package uncomment, How to fix it? – Q.Super Aug 29 '17 at 15:23
  • If you want to keep the package X.Y; statement, you need two things: 1 - create the package hierarchy (X/Y/MyClass) and 2 - update your running configuration on your IDE to launch the given X.Y.MyClass. – belka Aug 29 '17 at 16:00
0

A class's name is actually the package plus the class name. You cannot run HelloDemo in your first case, because that is not the class name. The class name is test.hello.HelloDemo.

By commenting out the package, you've essentially renamed the class to HelloDemo, so it runs.

In addition, when running the class with main, you must be in the correct location. For instance, if the class is test.hello.HelloDemo, your folder structure will be /test/hello/HelloDemo.java.

You must be in / and run test.hello.HelloDemo from there.

Christopher Schneider
  • 3,745
  • 2
  • 24
  • 38