我有一个ArrayIndexOutOfBoundsException,但我不知道为什么

问题描述 投票:0回答:2

我正在获取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数组中的最大索引数多一个。如果有人可以回答和帮助,将不胜感激。

java indexoutofboundsexception
2个回答
0
投票

strs[strs.length]不存在如果键入“ liam iljiah lucas”,则

strs[0].equalsIgnoreCase("liam") &&
strs[1].equalsIgnoreCase("elijah") &&
strs[2].equalsIgnoreCase("lucas")

strs[3]丢失


0
投票

[就像您正在做的一样,您必须在'for'中删除-1以使for(int x=0;x<strs.length;x++)

[以0开头的'for'时,必须将其视为迭代。

© www.soinside.com 2019 - 2024. All rights reserved.