Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Scanner#nextInt inside for loop keep throwing an exception?

I have been learning JAVA and i have a small doubt about the code :

class apple {
    public static void main(String[] args) {

        int[] num = new int[3];

        Scanner input = new Scanner(System.in);
        for (int i = 0; i < num.length; i++) {

            try {
                num[i] = input.nextInt();
            } catch (Exception e) {
                System.out
                    .println("Invalid number..assigning default value 20");
            num[i] = 20;
            }
        }

        for (int i = 0; i < num.length; i++) {
            System.out.println(num[i]);
        }
    }
}

I have written small program to handle exception, if user input is not Int throw an exception and assign default value. If i put scanner statement inside for loop, it works fine, but if i take it outside its assign the same value at which exception was thrown i.e i am entering char rather than int. But if i enter all integers it assign correct values in array.

Scanner input = new Scanner(System.in);

I hope u guys have understood my question.

like image 830
Nomad Avatar asked Jun 19 '14 06:06

Nomad


2 Answers

Scanner#nextInt doesn't advance past the input if it fails to parse an integer, so if you keep calling it after failure, it will keep trying to parse same input again, throwing InputMismatchException.

You can call Scanner#next, ignoring the string it returns, in your catch block to skip the invalid input:

try {
    num[i] = input.nextInt();
} catch (Exception e) {
    System.out
            .println("Invalid number..assigning default value 20");
    num[i] = 20;
    input.next();
}
like image 72
izstas Avatar answered Nov 19 '22 03:11

izstas


        try
        {
            num[i] = input.nextInt();
        }
        catch(InputMismatchException ip)
        {
            System.out.println("Invalid number..assigning default value 20");
            num[i] = 20;
            input.next();
        }
like image 32
Sivakumar Avatar answered Nov 19 '22 05:11

Sivakumar