Using int Instead Of String: public static void main (int[] args)(使用 int 代替字符串:public static void main (int[] args))
问题描述
我的印象是 main 方法必须具有public static void main (String[] args){}"的形式,你不能传递 int[] 参数.
I was under the impression that the main method had to have the form "public static void main (String[] args){}", that you couldn't pass int[] arguments.
但是,在 Windows 命令行中,当运行以下 .class 文件时,它接受 int 和 string 作为参数.
However, in windows commandline, when running the following .class file, it accepted both int and string as arguments.
例如,使用此命令将给出输出stringers":java IntArgsTest stringers"
For example, using this command will give the output "stringers": "java IntArgsTest stringers"
我的问题是,为什么?为什么这段代码会接受一个字符串作为参数而不会出错?
My question is, why? Why would this code accept a string as an argument without an error?
这是我的代码.
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",这是一个很大的不同.
Everything passed into main method, the one used by the JVM to start a program, is a String, everything. It may look like the int 1, but it's really the String "1", and that's a big difference.
现在有了您的代码,如果您尝试运行它会发生什么?当然它会编译得很好,因为它是有效的 Java,但是您的 main 方法签名与 JVM 要求的作为程序起点的签名不匹配.
Now with your code, what happens if you try to run it? Sure it will compile just fine since it is valid Java, but your main method signature doesn't match the one required by the JVM as the starting point of a program.
要运行您的代码,您需要添加一个有效的 main 方法,例如,
For your code to run, you'd need to add a valid main method like,
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);
}
}
然后在程序调用的时候传入一些数字.
And then pass some numbers in when the program is called.
这篇关于使用 int 代替字符串:public static void main (int[] args)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 int 代替字符串:public static void main (int[] args)
基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01