Java Test package does not exist

不羁岁月 提交于 2021-01-29 07:25:48

问题


Good morning, I have the file Test.java that is in /home

class Test {
    public static void main(String[] args) {
        prog.io.ConsoleOutputManager out=new prog.io.ConsoleOutputManager();
        pack1.A a=new pack1.A();
        out.println(a.toString());
    }
}

that gives me the error:

Test.java:3: error: package prog.io does not exist
prog.io.ConsoleOutputManager out=new prog.io.ConsoleOutputManager();
^
Test.java:3: error: package prog.io does not exist
prog.io.ConsoleOutputManager out=new prog.io.ConsoleOutputManager();
^
Test.java:5: error: package pack1 does not exist
pack1.A a=new pack1.A();
^
Test.java:5: error: package pack1 does not exist
pack1.A a=new pack1.A();
^
4 errors

pack1, pack2 and prog.io are in /home as well..Why it doesn't find them?


回答1:


Please make sure that you have set the classpath such that it can find the packages that you are using in your code.




回答2:


It is not sufficient to have the class files in the same directory. They must have the same package declaration as well.

Additionally /home must be part of your Classpath. If /home is your Classpath the files must be in subdirectories of /home:

/home/prog/io
    ConsoleOutputManager.class
/home/pack1
    A.class
/home
    Test.class

ConsoleOutputManager.java should have a declaration like package prog.io; before any import or class statements. A.java should have package pack1;.

With that, you can run your class informing the classpath using:

java -cp /home Test

And it will find its dependencies.

You can also place your dependencies in a JAR file with that same structure, and then include the JAR file in your classpath as well:

java -cp yourJar.jar:/home Test



回答3:


Check if you have package declaration in your ConsoleOutputManager class as well. It should be:

package prog.io;

as the first line in your file.




回答4:


Your source files are not organised into packages properly or the packages are missing. Your class file defines

prog.io.ConsoleOutputManager out=new prog.io.ConsoleOutputManager();
pack1.A a=new pack1.A();

so, JVM will look for class ConsoleOutputManager in prog.io package and class A in pack1 package and couldn't be found and throws package doesn't exist error. The solution is to add the missing packages sources in build path and keep your source files organised



来源:https://stackoverflow.com/questions/21967013/java-test-package-does-not-exist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!