• Post Reply Bookmark Topic Watch Topic
  • New Topic

Small Java problem  RSS feed

 
Jon Brasted
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.
I have just written this Java code and I am getting the following error:
'Exception in thread "main" java.lang.NoSuchMethodError: main'
If anyone can suggest what is going wrong, I will be grateful.

I get no error messages when I try and compile the code. I just get it when I try and execute it.
If I add "return -1" to the end of int.compare of the Fraction class, the error message 'unreachable statement' appears and compilation stops.
Does anyone know when and why to use "return -1"?
Many thanks,
Jon
 
Tim West
Ranch Hand
Posts: 539
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two separate issues here.
NoSuchMethodException - the method Main must be declared, as you have done, "public static void Main(String[] args)", (possibly with other modifiers like final). However, in order for it to be executed directly by the JVM, it must be in a class (usually declared 'public') that has the same name as the file in which it is located with a '.java' extension. So change the name of the file in which this code is located to TestFractions.java, or change the class name to match the name of the file.
With regard to 'return -1': the Java compiler does some primitive flow analysis to check that every statement is reachable. In this case, it sees that no matter what happens in the 'if (us > them)' statement, a 'return' statement is reached. Thus, flow could never reach your 'return -1;' statement. As you say, you can't compile a file if any statements are unreachable.
This flow analysis is relatively primitive and it is possible (and quite easy) to write unreachable statements. The extent of the analysis is defined somewhere in the JLS.
Cheers

-Tim
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about doing this in your compare() method:

As for your exception, do check that your classpath is set correctly.
There's no hard & fast rule in returning -1. At least not that I know of. Usually I return a -1 to indicate an error.
Hope this helps.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!