PDA

View Full Version : My next Java question




larswik
Sep 12, 2006, 11:50 PM
I wrote this from the example in the book.

import javax.swing.JOptionPane;

public class Greeter
{
public void sayHello()
{
JOptionPane.showMessageDialog(null, "Hello World","test", JOptionPane.INFORMATION_MESSAGE);
}
}

I then typed in the Terminal, javac Greeter.java the new command line popped up and I could see in the folder it created a file called Greeter.class

I then typed in, java Greeter

I was expecting a window to pop up sayign what it said in the book but here is what the termianl came back with.

larsg5s-power-mac-g5:~ larsg5$ java Greeter
Exception in thread "main" java.lang.NoSuchMethodError: main
larsg5s-power-mac-g5:~ larsg5$

I looked over the code and it looks ok, I think. The book didn't say to type this out I just tried it for fun, but I thought it would have worked.

Thanks,

-Lars



bousozoku
Sep 13, 2006, 12:44 AM
You need the other file that contains the main() function, that instantiates a Greeter object.

bookofjames
Sep 13, 2006, 12:52 AM
I think you need to seriously do some Java tutorials to get the hang of it.

This link may be of help.
http://java.sun.com/docs/books/tutorial/index.html

main runnable method is a pretty basic concept. In order to run any java class as an application, it needs to implement the void main() method.

-james

savar
Sep 13, 2006, 01:19 AM
The problem, as the error message says, is that there is no function called "main".

The way that the "java" command works is that it opens up your class and executes a static method called "main". Every application has to have this method. (Notice I didn't say "every class" -- there's a big difference. Java applets are also different.)

The easiest way to fix your program is to change the line

public void sayHello()

to

public static void main(String args[])

That should do it! Good luck--

larswik
Sep 13, 2006, 01:58 AM
Ahh, ok I see, I jumped a head. They were giving examples of coding and alot of what you said was in the coding on the previous page. I got a little excited when I saw that I could get a result on an external window instead of the Terminal replying "Hello World".

I guess it needed some of the coding before that one. It was not an example that I was supposed to write in the tutorial. But instead I thought it would be fun to see something work that wasn't a Terminal responce.

I will follow the book more closly since I seem to be getting myself into troube more often.

Thanks again folks!

-Lars