This is a simple code to get the character at the given index within the String. It is going through an infinite loop, I know that adding the scanner.nextLine() in the catch clause would eliminate the problem but I don't know the reason for that, so I would be grateful if anyone could explain it to me.
public class Main {
public static void main(String[] args) throws InterruptedException {
Scanner scanner = new Scanner(System.in);
System.out.print(" Original string = ");
String std=scanner.nextLine();
while(true){
System.out.println(" Enter the index ");
try {
int index = scanner.nextInt();
System.out.printf(" The character at position %d is %s", index, std.charAt(index));
}catch(InputMismatchException e){
System.out.println("Enter a valid number");
}
}