虽然循环是无限的

While Loop is Infinite

我正在编写计算税款的代码。我想要这个 while 段来确保用户输入一个有效的正整数。除非输入字符串,否则它会工作,然后进入无限循环。如何让它重复循环并让用户输入另一个输入,而不是无限循环?

    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

您需要将代码放在 try 块中,然后捕获 InputMismatchException,然后捕获输入行以清除缓冲区。

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

}

编辑:

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

     while(true) {
        System.out.println("Please enter number of dependents: ");
        try{
                int dependents = stdin.nextInt();
                if(dependents >= 0) {
                    //stops loop and moves on
                    break;
                }
                else {
                    System.out.println("Can't enter a negative number.");
                }
            }catch(InputMismatchException e){
                System.out.println("Invalid input");
                //catches input and clears
                stdin.nextLine();
           }
        }
}