线程“main”中的exceptionjava.lang.ArrayIndexOutOfBoundsException:0
public class TestSample { public static void main(String[] args) { System.out.print("Hi, "); System.out.print(args[0]); System.out.println(". How are you?"); } }
当我编译这个程序时,我收到此错误:
线程“main”中的exceptionjava.lang.ArrayIndexOutOfBoundsException:0
另外,为什么我不能有一个接受这样的int数组的args
:
public static void main(int[] args) {
1. ArrayIndexOutOfBoundsException:0
抛出它是因为args.length == 0
因此args[0]
超出了有效索引的数组范围( 了解有关数组的更多信息 )。
添加args.length>0
的检查以修复它。
public class TestSample { public static void main(String[] args) { System.out.print("Hi, "); System.out.print(args.length>0 ? args[0] : " I don't know who you are"); System.out.println(". How are you?"); } }
2.命令行args为int
您必须自己解析int[]
的参数,因为命令行参数仅作为String[]
传递。 为此,请使用Integer.parseInt(),但您需要进行exception处理以确保解析正常( 了解有关exception的更多信息 )。 Ashkan的回答告诉你如何做到这一点。
关于你问题的第二部分:
来自http://download.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html :
解析数字命令行参数
如果应用程序需要支持数字命令行参数,则它必须将表示数字的String参数(例如“34”)转换为数字值。 这是一个将命令行参数转换为int的代码片段:
int firstArg; if (args.length > 0) { try { firstArg = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument must be an integer"); System.exit(1); } }
- 该错误是因为程序启动时未添加任何参数。
- 由于被调用的main方法(通过JVM)的签名是
public static void main(String[] args)
而不是public static void main(int[] args)
如果你想要int,你需要从参数中解析它们。