0

I'm getting an ArrayIndexOutOfBoundsException, this is the full code

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();
    }
}

So I'm making a code where you input two names and if they're equal(ignoring cases) the program will print the first and middle initials and then the surname. I don't know why I'm getting this error since, as you can see, the value of variable x is definitely less than the length of the array. For some reason this error appears every time.

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)

Apparently the last index after the loop is always one more than the max number of indexes in the strs array. If someone can answer and help it would be greatly appreciated.

AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66
  • 1
    nevermind, I found the error. I was trying to print an element of the strs array by using its length as an index, which was the reason for the error. – uncultured programmer Jan 21 '20 at 14:09
  • Have another look at this code you have: System.out.print(strs[strs.length]); – RamblinRose Jan 21 '20 at 14:09
  • 2
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – maio290 Jan 21 '20 at 14:33

1 Answers1

0

strs[strs.length] does not exist If you type "liam iljiah lucas", then

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

strs[3] is missing

artmmslv
  • 139
  • 3
  • 12