1

I got this problem when running the following code in Java:

public class comparison
{
    public static boolean main(String[] args)
    {
        if (0.1 + 0.1 + 0.1 == 0.3) return true;
        else return false;
    }
}

Can anybody tell me why and how to modify the code?

4

2 回答 2

3

main method should be:

public static void main(String[] args)

and not:

public static boolean main(String[] args)

You probably wanted to do something like this:

 public static boolean check() 
 {
     if (0.1 + 0.1 + 0.1 == 0.3) return true;
        else return false;
 }

and then call it from the static main:

public static void main(String[] args)
{
    boolean result = check();
    //now you can print, pass it to another method.. etc..
}

Why main is void (doesn't return anything)?

  • Think about it. Once the main method finishes, it doesn't mean that the program finished. If it spawns a new thread it might be that these threads are still running.

Why main is public?

  • The main method is called by the JVM to run the method which is outside the scope of project.

Why main is static?

  • When the JVM calls the main method, there is no object existing for the class being called. So it has to have static method to allow this from class.
于 2013-03-30T21:13:33.240 回答
0

To be executable from the commandline, Java classes must implement a static method with signature

public static void main(String[] args) {

Because yours returns "boolean" instead of "void", the JVM doesn't know how to execute it. You'll need to either modify that method, or wrap it in another similar one with return type "void".

于 2013-03-30T21:14:55.060 回答