编译后应用程序无法找到主类

时间:2011-01-24 03:04:21

标签: java package javac

我用两个文件创建了一个非常简单的java示例:

Dog.java包含:

package com.greg.dog;

public class Dog {
    public void bark() {
        System.out.println("bark");
    }
}

TestDog.java包含:

package com.greg.dog;

public class TestDog {
   public static void main(String args[]) {
        Dog d = new Dog();
        d.bark();
    }
}

我在这两个文件的位置〜/ Desktop / test / src / com / greg / dog

当我编译它们时,Dog.java编译得很好,但是TestDog.java找不到我的Dog类:

user1@blackpearl:~/Desktop/test/src/com/greg/dog$ javac Dog.java 
user1@blackpearl:~/Desktop/test/src/com/greg/dog$ javac TestDog.java 
TestDog.java:6: cannot find symbol
symbol  : class Dog
location: class com.greg.dog.TestDog
        Dog d = new Dog();
        ^
TestDog.java:6: cannot find symbol
symbol  : class Dog
location: class com.greg.dog.TestDog
        Dog d = new Dog();
                    ^
2 errors

我在Ubuntu上,这是所有的java信息:

java version "1.6.0_0"
IcedTea6 1.3.1 (6b12-0ubuntu6.7) Runtime Environment (build 1.6.0_0-b12)
OpenJDK 64-Bit Server VM (build 1.6.0_0-b12, mixed mode)

任何想法我可能做错了什么?我需要导入Dog.java吗?我做错了吗?

更新

Per Anon的建议,我将目录更改为src目录,所有内容都编译完毕。但是,当我去运行TestDog.java时,我收到此错误:

user1@blackpearl:~/Desktop/test/src$ java com/greg/dog/TestDog.java 
Exception in thread "main" java.lang.NoClassDefFoundError: com/greg/dog/TestDog/java
Caused by: java.lang.ClassNotFoundException: com.greg.dog.TestDog.java
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:319)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:264)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:332)
Could not find the main class: com/greg/dog/TestDog.java. Program will exit.

1 个答案:

答案 0 :(得分:9)

Java编译器期望其他类位于与包相关的目录相对于从调用编译器的位置。

您希望使用以下内容进行编译:

user1@blackpearl:~/Desktop/test/src$ javac com/greg/dog/Dog.java
user1@blackpearl:~/Desktop/test/src$ javac com/greg/dog/TestDog.java