java - 我遇到了 ArrayIndexOutOfBoundsException,但我不知道为什么

标签 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();
    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/

相关文章:

java - Android N - 在运行时更改区域设置

java - StartupError > 如果 XML 文件有 ${<>} 那么服务器没有启动

java - 使用 Dom Java 对 XML 元素的文本内容进行标记

java - 如何使代码忽略 ArrayIndexOutOfBoundsException java

java - Kotlin - 从 Java 转换时出现 IndexOutOfBoundsException

java - 将功能分配给 Jbutton

Java文本分类问题

java - 我无法在其中输入高于 9 的值

java - Java读取CSV文件时出现空行

java - 从txt加载JTable数据