开发者

Exception in thread "main" java.lang.NoSuchMethodError: main [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Exception in thread “main” java.lang.NoSuchMethodError: main

public class m
{
    int a; //class variable


    void f1()
    {
       int b=10;
       System.out.println(a);
       System.out.println(b);
    }
}
class B
{
   public static void main(String args[])
   {
      m ob=new m(); //object created
      ob.f1(); //calling f1 meth开发者_Go百科od

   }
}


I'll guess.

You are trying to invoke:

java m

Since you defined you main method in class B you should call

java B

To execute it.

Here's my test:

$cat >m.java<<. 
> public class m
> {
>     int a; //class variable
>     void f1()
>     {
>        int b=10;
>        System.out.println(a);
>        System.out.println(b);
>     }
> }
> class B
> {
>    public static void main(String args[])
>    {
>       m ob=new m(); //object created
>       ob.f1(); //calling f1 method
>    }
> }
> .
$javac m.java 
$java m 
Exception in thread "main" java.lang.NoSuchMethodError: main
$java B
0
10
$

If you see, invoking java B prints 0 10as expected.


Main needs to be in the top-level class whose name corresponds to the filename - so if "m" is the name of your file that's where main needs to be. Note that by convention class names start with an uppercase letter.


Did you invoke the Java program with java m? The main method is defined in the class B, not m, therefore, you need the java B command to invoke it. It may be confusing if you reasoned by "Same as filename.".

Also, putting two classes in one file may be a bad practice.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜