如何结合这两个do / while语句

时间:2016-03-29 15:19:38

标签: java while-loop do-while

我需要帮助结合这两个do / while循环。我尝试使用switch语句和do / while循环创建一个读取gradereport的程序。

action

2 个答案:

答案 0 :(得分:0)

你可以做同样的事情,

do{

            System.out.print("Enter a numeric grade (0 to 100): ");
            grade = scan.nextInt();
            if(grade < 0 || grade>100){
                System.out.println("Error: You must enter an integer between 0 and 100");
                tries++;
                if(tries==4){
                    tries = 0;
                    System.out.println("You have attempted upto max limit");
                    System.out.println("Enter a numeric grade (0 to 100): ");
                    grade = scan.nextInt();
                    if(grade>=0 && grade<=100)
                        break;
                        System.out.println ("Error: You must re-enter an integer between 0 and 100");   
               }

            }
            else{
                System.out.println("Hi, your grade point is "+grade);
                break;
            }
        }while(true);

答案 1 :(得分:0)

你可以这样做:

int grade, tries = 0;

for ( ; ; ) {
    System.out.print("Enter a numeric grade (0 to 100): ");
    grade = scan.nextInt();

    if (grade >= 0 && grade <= 100) {
        if (tries == 4) {
            break;
        } else {
            System.out.println("Hi, your grade point is " + grade);
            break;
        }
    } else {
        if (tries == 4) {
            System.out.println("Error: You must re-enter an integer between 0 and 100");
        } else {
            System.out.println("Error: You must enter an integer between 0 and 100");
            tries++;

            if (tries == 4) {
                System.out.println("You have attempted upto max limit");
            }
        }
    }
}