【发布时间】:2020-05-07 14:46:20
【问题描述】:
我得到一个 ArrayIndexOutOfBoundsException,这是完整的代码
public static void main(String[] args){
input();
}
static void input(){
Scanner scan=new Scanner(System.in);
System.out.println("Please enter the first name");
String name1=scan.nextLine();
System.out.println("Please enter the second name");
String name2=scan.nextLine();
boolean retval=name1.equalsIgnoreCase(name2);
if(retval){
String[] strs=name1.split(" ");
for(int x=0;x<strs.length-1;x++){
String con=Character.toString(strs[x].charAt(0));
System.out.print(con+ " ");
}
System.out.print(strs[strs.length]);
}
else{
input();
}
}
所以我正在编写一个代码,您可以在其中输入两个名字,如果它们相等(忽略大小写),程序将打印第一个和中间的首字母,然后是姓氏。我不知道为什么会出现此错误,因为如您所见,变量 x 的值肯定小于数组的长度。由于某种原因,这个错误每次都会出现。
run:
Please enter the first name
Liam Elijah Lucas
Please enter the second name
liam elijah lucas
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Exercise3.input(Exercise3.java:34)
at Exercise3.main(Exercise3.java:16)
L E Java Result: 1
BUILD SUCCESSFUL (total time: 15 seconds)
显然循环之后的最后一个索引总是比 strs 数组中的最大索引数多一。如果有人能回答并提供帮助,将不胜感激。
【问题讨论】:
-
没关系,我发现了错误。我试图通过使用它的长度作为索引来打印 strs 数组的元素,这就是错误的原因。
-
再看看你的代码:System.out.print(strs[strs.length]);
标签: java indexoutofboundsexception