简体   繁体   中英

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 ie 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.

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();
}
        try
        {
            num[i] = input.nextInt();
        }
        catch(InputMismatchException ip)
        {
            System.out.println("Invalid number..assigning default value 20");
            num[i] = 20;
            input.next();
        }

A better code can be that you can check that whether the next value is integer or not , So you don't even need to catch exceptions:

   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++) 
     {
             if(input.hasNextInt())
             {
                  num[i] = input.nextInt();
             }

            else
            {
                System..out.println("non integer value.. will assign it default value 20");
                num[i]=20;
                input.next();
            }
    }

    for (int i = 0; i < num.length; i++) {

        System.out.println(num[i]);
    }


  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM