AeriaGlorisia AeriaGlorisia - 1 month ago 9
Java Question

String index out of range - Why is this occurring?

(Please keep in mind I have only been studying java for under a month on my own)

I am trying to make a program that simply tells you the last char of the name you give the program. Here is my code:

import java.util.Scanner;


public class LastCharacter {


public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("hey");
String name = reader.nextLine();
lastChar(name);
}

public static char lastChar(String text) {
char lastChar = '\0';;
int i = 0;
for (i = 0; i <= text.length(); i++) {
lastChar = text.charAt(i);

}
System.out.println(lastChar);
return lastChar;
}


}

Error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at LastCharacter.lastChar(LastCharacter.java:19)
at LastCharacter.main(LastCharacter.java:11)


Java Result: 1

I also know this can be made by subtracting the length of the string by 1, however I would like to know why this method isn't working. I don't really know how to word this but do strings and chars not get along? (pls dont make fun of me)

Thanks!

Answer

Java strings start at a base index of 0. Therefore, this line: for (i = 0; i <= text.length(); i++) { is trying to access an index that doesn't exist. The string main only goes from 0 to 3. So, when you try to access index 4, you get the out of bounds error.

Replace this line: for (i = 0; i <= text.length(); i++) {

With this: for (i = 0; i < text.length(); i++) { to fix the problem.

Comments