使用int而不是String:public static void main(int args)

我的印象是main方法必须具有“public static void main(String [] args){}”forms,你无法传递int []参数。

但是,在Windows命令行中,运行以下.class文件时,它接受int和string作为参数。

例如,使用此命令将输出“stringers”:“java IntArgsTest stringers”

我的问题是,为什么? 为什么这段代码会接受一个字符串作为参数而没有错误?

这是我的代码。

public class IntArgsTest { public static void main (int[] args) { IntArgsTest iat = new IntArgsTest(args); } public IntArgsTest(int[] n){ System.out.println(n[0]);}; } 

传递给main方法的所有内容,即JVM用来启动程序的方法,都是String,一切。 它可能看起来像int 1,但它确实是字符串“1”,这是一个很大的区别。

现在使用您的代码,如果您尝试运行它会发生什么? 当然它会编译得很好,因为它是有效的Java,但是你的主方法签名与JVM作为程序起点所需的方法签名不匹配。

要运行代码,您需要添加一个有效的main方法,比如

 public class IntArgsTest { public static void main(int[] args) { IntArgsTest iat = new IntArgsTest(args); } public IntArgsTest(int[] n) { System.out.println(n[0]); }; public static void main(String[] args) { int[] intArgs = new int[args.length]; for (int i : intArgs) { try { intArgs[i] = Integer.parseInt(args[i]); } catch (NumberFormatException e) { System.err.println("Failed trying to parse a non-numeric argument, " + args[i]); } } main(intArgs); } } 

然后在调用程序时传入一些数字。

好吧,你可以使用名称为main任何方法,包含任意数量的参数。 但是JVM将使用精确签名public static void main(String[])来查找main方法。

您定义的main方法只是该类的另一种方法。

我现在无法访问Windows,但让我暂时尝试一下。 我确实尝试过Fedora,当然我遇到了以下exception:

 Exception in thread "main" java.lang.NoSuchMethodError: main 

请注意,由于上述原因,该类将编译正常。

更新:我在Windows 7上测试过,结果是一样的。 我很惊讶你说它对你有用。

此代码实际上不会运行。 当代码编译时(因为你不需要main来编译),当你尝试运行它时,你会得到一个"Main method not found"错误。

更好的是,当我跑它说它

  "please define the main method as: public static void main(String[] args) 

此代码包含public static void main(int [] args) ,它不起作用。 因为JVM将参数值作为字符串参数。 它不需要任何int参数。 因此,如果我们想要一个int参数意味着我们必须将字符串参数转换为整数参数。 要运行此代码,需要有效的main方法 (例如: public static void main(String args [])