0

因此,对于我的编程作业,用户必须输入等级数,但我们必须检查输入并返回正确的错误。该数字必须是正数,并且程序需要在错误之间进行区分并给出正确的响应并将其循环回来,直到输入正确的数字。我得到了错误检查部分,但我无法让程序继续下一部分。任何帮助,将不胜感激

do {
        System.out.println("Enter number of grades");
        if (input.hasNextInt()){
             numGrade = input.nextInt();

            if (numGrade < 0){
                 System.out.println("Your number of grades needs to positive! Try again");
                 count1++;
                 continue;
            }   
         }
        else{
            System.out.println("You did not enter a number! Try again");
            count1++;
            input.next();
            continue;
         }


}while (count1 > 0);
4

1 回答 1

0

尝试这个,

//use a boolean to tell the loop to continue or not
boolean cont = true;

do {


    System.out.println("Enter number of grades");

    if (input.hasNextInt()){

        numGrade = input.nextInt();

        //I assume 0 is a valid response (not a negative int)
        if (numGrade <= 0){
            System.out.println("Your number of grades needs to positive! Try again");
            continue;
        }
        else {
            cont = false;
            System.out.println("Your input is valid! Value entered is " + numGrade);
        }
    }
    else {
        System.out.println("You did not enter a number! Try again");
                input.next();
                continue;
    }
}
while (cont);
于 2015-10-14T03:27:00.203 回答