简体   繁体   中英

The declared package "a" does not match the expected package ""

Having this file schema:

folder "a"
        |
        |_____ MyClass.java

Where my ".java" file has this code:

package a;

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello world");

    }
}

I was wondering the reason why I get this error (I'm using visual studio, I say it in case it is related to my error):

The declared package "a" does not match the expected package "".

I've noticed that sometimes when I reopen my folder It suddenly works, however other times it doesn't.

I don't know why this happens, I believe the reason it's related to visual studio but it goes further of it, since when I try to compile it, as said, sometimes It works, others don't.

Telling me this error:

Error: Could not find or load main class MyClass
Caused by: java.lang.NoClassDefFoundError: a/MyClass (wrong name: MyClass)
package a;

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello world");

    }
}

It depends from where you are referencing the class. If a is a subfolder and you are trying to compile MyClass.java from within a it won't work (unless you specify the correct folder like ./.. or similar. Packages are relative to some root folder or other package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM