使用int代替String:public static void main(int [] args)
问题内容:
我的印象是main方法必须具有“ public static void main(String [] args){}”形式,您不能传递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);
}
}
然后在调用程序时传递一些数字。