【问题标题】:I'm having an ArrayIndexOutOfBoundsException and I don't know why我有一个 ArrayIndexOutOfBoundsException 我不知道为什么
【发布时间】: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 数组中的最大索引数多一。如果有人能回答并提供帮助,将不胜感激。

【问题讨论】:

标签: java indexoutofboundsexception


【解决方案1】:

strs[strs.length] 不存在 如果你输入“liam iljiah lucas”,那么

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

strs[3] 不见了

【讨论】:

    猜你喜欢
    • 2013-11-07
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多