简体   繁体   中英

The declared package “” does not match the expected package “(file name)”

I'm new to Java and I'm using Visual Studio Code. When I run the code it works fine, but every program in java (even a basic Hello World program) gives me this error.

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

I didn't find any solutions on internet and I don't know how to fix this.

here is the code:

public class helloworld {
    public static void main(String[] args) {
        
        System.out.println("hello world");
        
    }
}

Based on your compiler error and the code you showed, you have the following folder/package structure in the project you have created:

src
|
|-helloWorld
       |
       | helloworld.java

If that's the case, the "expected package" is the full package definition your java file is defined in, in this case, "helloWorld"

If you had this other folder structure:

src
|
|-helloWorld (folder/package)
       |
       | subfolder (subfolder/package)
                 |
                 | helloworld.java

then your expected package for the class helloworld would be helloWorld.subfolder

To actually define that package in the .java file, you must write the following as the first code line of the file (this is mandatory):

package fullpackage;

In your example, this would be:

package helloWorld;

The full code example as I can see it, would be for you something like...

package helloWorld;
public class helloworld {
   // the rest of your main method and code here
}

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