线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:0 [英] Exception in thread "main" java.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?");
}
}
当我编译这个程序时,我收到此错误:
When I compile this program, I get this error:
线程main中的异常java.lang.ArrayIndexOutOfBoundsException:0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
另外,为什么我不能有一个接受这样的int数组的 args
:
public static void main(int[] args) {
推荐答案
1。 ArrayIndexOutOfBoundsException:0
它被抛出,因为 args.length == 0
因此 args [0]
超出了有效索引的数组范围(了解有关数组的更多信息)。
It was thrown because args.length == 0
therefore args[0]
is outside the arrays range of valid indices (learn more about arrays).
添加支票 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。命令行参数为int
您必须自己将参数解析为 int []
命令行参数仅作为 String []
传递。要执行此操作,请使用整数.parseInt()但您需要进行异常处理以确保解析正常(了解更多信息的例外)。 Ashkan的回答告诉你如何做到这一点。
You will have to parse the arguments to int[]
yourself as the command line arguments are passed only as a String[]
. To do this, use Integer.parseInt() but you will need exception handling to make sure the parsing went OK (learn more about exceptions). Ashkan's answer shows you how to do this.
这篇关于线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!