Mon*_*dia 4 java command-line program-entry-point arguments cmd
我的印象是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]);};
}
Run Code Online (Sandbox Code Playgroud)
Hov*_*els 16
传递给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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在调用程序时传入一些数字.