0

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");
        }
    }
Arshiya
  • 1
  • 1
  • 1
    `int index = scanner.nextInt();` - when the next token is not a `int` you think the thing that is not an int is consumed. It is **not**. However, adding `scanner.nextLine()` in the `catch` clause consumes the token that you just determined is not an `int`. Better to use something like `if (scanner.hasNextInt())` before trying to read an `int`. Notice you would still have to consume things that are not ints to avoid causing an infinite loop. – Elliott Frisch Jan 24 '21 at 20:42

0 Answers0