开发者

After compile application fails to find main class

开发者 https://www.devze.com 2023-02-06 02:50 出处:网络
I made a really simple java example with two files: Dog.java contains: package com.greg.dog; public class Dog {

I made a really simple java example with two files:

Dog.java contains:

package com.greg.dog;

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

TestDog.java contains:

package com.greg.dog;

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

I have these two files in the location ~/Desktop/test/src/com/greg/dog

When I compile them, Dog.java compiles fine, but TestDog.java can't find my Dog class:

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

I'm on Ubuntu, here's all the java information:

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)

Any ideas what I could be doing wrong? Do I need to import Dog.java? Am I doing packages wrong?

Update

Per Anon's suggestion, I changed directories to the src directory and everything compiles. However when I go to run TestDog.java I get this error:

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 jav开发者_开发问答a.lang.ClassLoader.loadClassInternal(ClassLoader.java:332)
Could not find the main class: com/greg/dog/TestDog.java. Program will exit.


The Java compiler expects other classes to be in the package-appropriate directory relative to where the compiler is invoked from.

You'll want to be compiling using something like:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号