簡體   English   中英

我有一個 ArrayIndexOutOfBoundsException 但我不知道為什么

[英]I'm having an ArrayIndexOutOfBoundsException and I don't know why

我收到一個 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[strs.length]不存在 如果您輸入“liam iljiah lucas”,則

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

缺少strs[3]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM