开发者

Static Error: This class does not have a static void main method accepting String[]

开发者 https://www.devze.com 2023-02-05 15:58 出处:网络
Since I want the user to enter numb开发者_如何学Goers instead of Strings I used public static void main(Integer[] args)

Since I want the user to enter numb开发者_如何学Goers instead of Strings I used

public static void main(Integer[] args)

So, why is this wrong?


The signature on your main method MUST be:

public static void main(String[] args)

You don't have any other option. You may parse those strings as integers if you need to, via Integer.parseInt(someString)


Main is special since it has to be present to start the program, so it's required to have a fixed signature. Under the hood, the java runtime looks for the magic signature to start the program. The magic signature is

public static void main(String[] args)

If you want to get Integers, you'll need to parse them out after the fact, using

Integer.parseInt( x );


You can only have an array of String[] for your main method (unless you overload it, but let's not get into the details for now :-D).

However, you can change each element of the String[] args into an int by using Integer.parseInt, something like

public static void main(String[] args)
{
 int[] values = new int[args.length];
 for (String arg : args)
 {
  //Get or do something with the integer value here
 }
}

This is because the underlying platform only knows how to pass Strings to your program. When you open up a command prompt or terminal and do:

>java MyClass 3 4 5

It doesn't know that you want ["3","4","5"] treated like integers. It leaves dealing with the Strings up to the program.


When the JVM loads your class and tries to execute it, it looks for the method main() with the signature

public static void main (String[] args) ...

Anything else is unaccptable. If you are expecting integers, use the Integer.parseInt() method to convert the input Strings to integers, as Zach mentioned. I'd put that conversion in a try-catch block to catch NumberFormatException, and have a

System.err.println ("This class accepts Integer arguments only"); 

in the corresponding catch block. Regards, - M.S.


You'll need to accept a string array, and convert the strings to integers at runtime. Just the way it works...


the method signature for main is always (String[] args). If you are going to get Integers, then you have to convert the args[] to int using the snippet below

  int aInt = Integer.parseInt(args[0]);
0

精彩评论

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