I am attempting to write a program that when a user inputs a word, then an index, which causes the program to display the character at the given index, or gives error telling the user that the index given is too large . Whenever I run the code and put an index that is too large, I get an error message from the java instead. Any help is appreciated!
import java.util.Scanner;
public class scratch {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.printf("Enter a word:");
String word = reader.next();
Scanner letter = new Scanner (System.in);
System.out.printf("Enter an index:");
int index = letter.nextInt();
char inputIndex = word.charAt(index);
int length = word.length();
if (index < length - 1 ) {
System.out.printf("In word \"%s\", the letter at index"
+ " \"%2d\" is \'%c\'.\n"
,word, index, inputIndex );
} else {
System.out.printf("too big");
}
reader.close();
letter.close();
}
}
Error message: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3 at java.base/java.lang.StringLatin1.charAt(Unknown Source) at java.base/java.lang.String.charAt(Unknown Source) at scratch.main(scratch.java:15)