FAR
FAR

Reputation: 13

try catch on looping (differnet between InputMismatchException and ArrayIndexOutOfBoundsException)

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); ?

Upvotes: 1

Views: 338

Answers (1)

Maroun
Maroun

Reputation: 95958

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.

Upvotes: 1

Related Questions