javapackagejava-package

Error `The declared package "part2.stage2" does not match the expected package ""` with correct package name


So I have a Competitor.java file on path: /home/john/javaStuff/CMTR/src/part2/stage2/Competitor.java. I have VSCode open in the CMTR. So CMTR is my current working directory if that info is necessary.

The only content I have in the CompetorList.java file is

package part2.stage2;

It seems that the error expects me to not have the package keyword there. If I remove it, it works fine indeed. But I want to use packages. After some Googling, Java does not require a default package, so I don't know why it wants me to have no package. The file path matches and all other packages work, just not this. Here's the tree of of structure: I have other Java files in different stages eg. stage 1 with the same layout and they all work including that of part1.stage1. But part2.stage2 is just misbehaving.

Screenshot of IDE


Solution

  • It's because in the file ManagerTest, the package is declared as package testing;. So the extension inferred the source root to be src/part2/stage2.

    What you can do is:

    Change the package name to:

    enter image description here

    And then reload VS Code window.


    Or, if you want to disable the auto source root inference and want to specify it by your own. You can leverage the setting java.project.sourcePaths

    Remember to set it in the WORKSPACE scope.