而Loop是无限的

时间:2017-10-12 01:36:48

标签: java while-loop infinite-loop

我正在研究计算税收的代码。我希望在分段时确保用户输入有效的正整数。除非输入字符串,否则它会起作用,然后进入无限循环。如何让它重复循环并让用户输入另一个输入,而不是无限循环?

    int dependentsRerun = 0;//makes user enter valid input for dependents
    while(dependentsRerun == 0) {
        System.out.println("Please enter number of dependents: ");
        if(stdin.hasNextInt()) {
            int dependents = stdin.nextInt();
            if(dependents>=0) {
                dependentsRerun = 1;
            }//end if dependents>=0
            else {System.out.println("Invalid input");}//dependents negative
        }//end if hasNextInt
        else {System.out.println("Invalid input");}//dependents not an integer
    }//end while dependentsRerun

1 个答案:

答案 0 :(得分:0)

你需要在try块中包围你的代码,然后捕获InputMismatchException,然后捕获输入行,以便清除缓冲区。

https://firebasestorage.googleapis.com/b/<YOUR_BUCKET>/o/<PERCENT_ENCODED_PATH_TO_FILE>?alt=media

编辑:

这可能是构建循环的更好方法

    int dependentsRerun = 0;//makes user enter valid input for dependents
    while(dependentsRerun == 0) {
        System.out.println("Please enter number of dependents: ");
        try{
                int dependents = stdin.nextInt();
                if(dependents>=0) {
                    dependentsRerun = 1;
                }
                else {
                    System.out.println("Invalid input");
                }
            }catch(InputMismatchException e){
                System.out.println("Invalid input");
                //catches input and clears
                stdin.nextLine();
           }
        }

}