简体   繁体   中英

How to combine these two do/while statement

I need help combining these two do/while loops. I trying to make a program that reads gradereport with the switch statement and do/while loops.

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++;
    }
    else{
        System.out.println("Hi, your grade point is " + grade);
        break;
    }
} while (tries <= 3);

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

    do
    {
        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");   
    } while (true);
}

you can do something likewise,

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

You could do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM