Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Program from "Head First Java" won't run

 
david jines
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the following program from page 36 compile but not run? It sets the message: Exception in thread "main" java.lang. NoSuchMethodError:main.

code
--------------------------------------------------------------------------- class Dog {

int size ;
String breed ;
String name;

public void bark() {
System.out.println ("Ruff! Ruff!");
}
}

class DogTestDrive {

public static void main(String[] args) {

Dog d = new Dog() ;

d.size = 40;

d.bark();
}
}
------------------------------------------------------------------------


If I remove the class DogTestDrive line and appropriate braces it then runs but that seems to be defeating the intent of the lesson.
 
sanjay baba
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think you are compiling class Dog and trying to run it.....you need to compile DogTestDrive and run the same......
 
Jesus Angeles
Ranch Hand
Posts: 2068
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

What is the intent on that topic?

Is that the exact code?

How did you compile it? run it?
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Did you save each of these in its own file? Or did you save both of them in a file named DogTestDrive.java ?

When you try to run it, be sure that you type
java DogTestDrive
and not
java Dog

What is the exact error message?
 
Harish Tiruvile
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Class which define main method should be public....make DogTestDrive class as public ...it will execute properly...

FYI


class Dog {

int size ;
String breed ;
String name;

public void bark() {
System.out.println ("Ruff! Ruff!");
}
}

public class DogTestDrive {

public static void main(String[] args) {

Dog d = new Dog() ;

d.size = 40;

d.bark();
}
}
 
suji kumar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
dear harish,
Class which has main method need not be public.
The exception may be due to, David must have tried to run : java DOG , which doesnt have main method , instead of DOGTESTDRIVE
 
david jines
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much for your help. The last program I wrote and ran was either Fortran or Algol back in 1969 so it never crossed my mind to start anywhere but at the first line of the program. Starting with DogTestDrive instead of Dog did the trick.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic