我收到 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 数组中的最大索引数大 1。如果有人可以回答并提供帮助,我们将不胜感激。
最佳答案
strs[strs.length]
不存在
如果您输入“liam iljiah lucas”,则
strs[0].equalsIgnoreCase("liam") &&
strs[1].equalsIgnoreCase("elijah") &&
strs[2].equalsIgnoreCase("lucas")
strs[3]
缺失
关于java - 我遇到了 ArrayIndexOutOfBoundsException,但我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59842818/