Java I';我有一个ArrayIndexOutOfBoundsException,我没有';我不知道为什么
我得到一个ArrayIndexOutOfBoundsException,这是完整的代码Java I';我有一个ArrayIndexOutOfBoundsException,我没有';我不知道为什么,java,indexoutofboundsexception,Java,Indexoutofboundsexception,我得到一个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();
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();
}
}
显然,循环后的最后一个索引总是比strs数组中的最大索引数多一个。如果有人能回答并提供帮助,我们将不胜感激。
strs[strs.length]
不存在
如果你输入“liam iljiah lucas”,那么
strs[3]
丢失了不过,我发现了错误。我试图通过使用strs数组的长度作为索引来打印它的一个元素,这就是错误的原因;这回答了你的问题吗?
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[0].equalsIgnoreCase("liam") &&
strs[1].equalsIgnoreCase("elijah") &&
strs[2].equalsIgnoreCase("lucas")