简体   繁体   中英

Multiple conditions for a Do..While Loop in Java

right basically I am implementing a do while loop. A user is asked to enter a value, and a value is returned back - this is using nested If statements within the do loop. At the end of the loop I am asking whether they want to enter another value, yes or no basically. Here is my code below, I essentially need a way of when the question is asked at the end to perform like...

"Would you like to enter another value?" - "no" - terminates "Would you like to enter another value?" - "yes" - loop around "Would you like to enter another value?" - any other value eg "maybe" - ask the question again.

The code:

import java.util.Scanner;

public class More_Grades {


public static void main (String [] args) {

    Scanner scan = new Scanner(System.in);
    String A = "Your grade is: ";

    int grade = 0;
    String y;

    do {
        System.out.println("Please Enter Your Grade: ");
        grade = scan.nextInt();
        if (grade < 40) {
            System.out.println(A+"Fail");
        }
        else if (grade >= 40 && grade <= 49) {
            System.out.println(A+"3rd");
        }
        else if (grade >= 50 && grade <= 59) {
            System.out.println(A="2/2");
        }
        else if (grade >= 60 && grade <= 69) {
            System.out.println(A+"2/1");
        }
        else if (grade >= 70 && grade < 100) {
            System.out.println(A+"1st");
        }
        else if(grade >100) {
            System.out.println("Invalid grade,Enter a value below 100.");
        }
        System.out.println("Would you like to Enter Another? Y/N");
        y = scan.next();

    }while (y.equals("yes"));
    scan.close();
    System.out.println("Thank-You.");
}

}

You just need another do-while inside your current loop to repeat the question:

do {
    ...
   do {
       System.out.println("Would you like to enter another? (yes/no)");
       answer = scan.next();
   } while (!Arrays.asList("yes", "no").contains(answer));
} while (answer.equals("yes");

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