1

I have this code

package example;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Example {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int rep;
    int[] arraya = new int[2];
    do {
        try {
            rep = 0;
            System.out.print("input col :");
            int kol = input.nextInt();
            System.out.print("input value :");
            int val = input.nextInt();
            arraya[kol] = val;
        } catch (InputMismatchException e) {
            System.out.println("input must integer");
            rep = 1;
            input.next();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("out of range");
            rep = 1;
        }
    } while (rep == 1);
}
}

Why must I add input.next(); in catch(InputMismatchException e); to avoid endless looping?

Why in catch(ArrayIndexOutOfBoundsException e); do not need input.next(); to avoid endless looping?

In catch(ArrayIndexOutOfBoundsException e);, looping runs well without input.next(); why it is different from catch(InputMismatchException e); ?

Maroun
  • 94,125
  • 30
  • 188
  • 241
FAR
  • 13
  • 2
  • You shouldn't catch `ArrayIndexOutOfBoundsException`. You should fix the bug that causes it. – user207421 Jan 12 '15 at 09:19
  • @EJP thanks for your reply, i made that code to know what the different between `ArrayIndexOutOfBoundsException` and `InputMismatchException` why they treated different in looping – FAR Jan 12 '15 at 10:43

1 Answers1

1

Because if you enter a non-integer character, int kol = input.nextInt(); will not wait for the user to enter an int again, it'll keep trying to read the character that was entered previously since it wasn't consumed.

If you enter an out-of-bounds int, it will be consumed, and the next int be read in the next iteration.

Maroun
  • 94,125
  • 30
  • 188
  • 241