Beginning Java programmer 10.4

Discussion in 'Mac Programming' started by jsprice2, Mar 20, 2007.

  1. macrumors newbie

    Joined:
    Nov 15, 2006
    #1
    java beginner - OS 10.4 - using terminal and Head First Java text to self learn - old BASIC person from years ago -

    get the following error:
    Exception in thread "main" java.lang.NoClassDefFoundError: GoodDogTestDrive/class

    code below - would also like to know how to run code with 2 classes - everything is in the same directory
    -------------

    class GoodDog {
    private int size;

    public int getSize() {
    return size;
    }
    public void setSize(int s) {
    size = s;
    }
    void bark() {
    if (size > 60) {
    System.out.println("Woof Woof !");
    } else if (size > 14) {
    System.out.println("Ruff Ruff!");
    } else {
    System.out.println("Yip Yip!");
    }
    }
    }

    class GoodDogTestDrive {
    public static void main (String[ ] args) {
    GoodDog one = new GoodDog();
    one.setSize(70);

    GoodDog two = new GoodDog();
    two.setSize(8);

    System.out.println("Dog one: " + one.getSize());
    System.out.println("Dog two: " + two.getSize());

    one.bark();
    two.bark();
    }
    }
     
  2. macrumors 6502a

    Joined:
    Sep 3, 2005
    Location:
    Cramlington, UK
    #2
    Is your file named GoodDogTestDrive.java?

    b e n

    EDIT: I've put all the code you posted in a file called GoodDogTestDrive.java and it compiles and runs fine.
     
  3. macrumors member

    Joined:
    Oct 19, 2006
    Location:
    Atlanta, GA
    #3
    I think GoodDogTestDrive needs to be declared public.
     
  4. macrumors 68020

    ChrisBrightwell

    Joined:
    Apr 5, 2004
    Location:
    Huntsville, AL
    #4
    Don't include the ".class" in your java command.

    For example, to build and run HelloWorld.java:

    Code:
    class HelloWorld
    {
      public static void main (String args[])  
      {
        System.out.println("Hello, world!");
      }
    }
    Then in terminal, these are your commands:
    Code:
    % javac HelloWorld.java
    % java -cp ./ HelloWorld
    The problem with using "java HelloWorld.class" is that the . is a package/file separator, so it looks for ./HelloWorld/class.class ... which won't exist. :)

    Also, the "-cp ./" is just to ensure that it looks in the local directory for the .class file to run. Some JVMs add automatically search there, but not all do, so it's usually a good practice to explicitly set the classpath.

    Hope this helps.
     
  5. macrumors 6502

    Joined:
    Oct 24, 2005
    #5
    exactly what he said. This is a common exception. If you run your program without the .class then its a classpath issue.
     
  6. thread starter macrumors newbie

    Joined:
    Nov 15, 2006
    #6
    Beginning Java programmer 10.4

    Thanks for alll the help. I did put .class at the end of command line and it was the problem.
     

Share This Page