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.