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

不打扰是莪最后的温柔 提交于 2020-06-08 17:14:06

问题


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.


回答1:


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();
}



回答2:


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



回答3:


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]);
    }


  }


来源:https://stackoverflow.com/questions/24300314/why-does-scannernextint-inside-for-loop-keep-throwing-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!