我的印象是,main方法必须具有"public static void main (String[] args){}“的形式,您不能传递int[]参数。
然而,在windows命令行中,当运行下面的.class文件时,它同时接受整数和字符串作为参数。
例如,使用以下命令将得到输出" 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]);};
}发布于 2012-04-17 08:49:04
传递给main方法的所有东西都是字符串,所有东西都是字符串。它可能看起来像int1,但它实际上是字符串"1",这是一个很大的区别。
现在,使用您的代码,如果您尝试运行它会发生什么?当然它会编译得很好,因为它是有效的Java,但是您的main方法签名与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);
}
}然后在调用程序时传入一些数字。
发布于 2012-04-17 08:51:07
好的,你可以有任何名为main的方法和任意数量的参数。但是JVM将查找具有确切签名public static void main(String[])的main方法。
您定义的main方法只是该类的另一个方法。
我现在无法访问Windows,但让我稍后尝试。我确实尝试了Fedora,当然我得到了以下异常:
Exception in thread "main" java.lang.NoSuchMethodError: main请注意,由于上述原因,该类可以很好地编译。
更新:我在Windows7上测试了,结果是一样的。我很惊讶你说这对你很有效。
发布于 2012-04-17 08:50:50
这段代码实际上不会运行。在编译代码时(因为编译时不需要main ),当您尝试运行它时,会得到一个"Main method not found"错误。
更妙的是,当我运行它的时候,它说
"please define the main method as: public static void main(String[] args)https://stackoverflow.com/questions/10183611
复制相似问题