简体   繁体   中英

Repeating after wrong answer

Today I was messing around and I was trying to create a multiple choice test. I got this far and it works. I was wondering though, how would I make it repeat the question if the user got the answer wrong? If anyone could help me out that would be fantastic! Thanks!

import java.util.Scanner;
public class multipleChoiceTest {

    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);

        System.out.println("What color is the sky?");
        System.out.println("A. Blue");
        System.out.println("B. Green");
        System.out.println("C. Yellow");
        System.out.println("D. Red");
        String userChoice = myScanner.nextLine();

        if (userChoice.equalsIgnoreCase("a")) {
            System.out.println("You're right!");
        } else {
            System.out.println("You're wrong! Try Again.");

        }
     } 

You can use While statement in this case! Let's look at it this way: as long as the user doesn't answer correctly, you will not continue. Now change "as long as" with "while(...)" We'll get this code:

Scanner myScanner = new Scanner(System.in);
System.out.println("What color is the sky?");
System.out.println("A. Blue");
System.out.println("B. Green");
System.out.println("C. Yellow");
System.out.println("D. Red");
String userChoice = myScanner.nextLine();

while(! userChoice.equalsIgnoreCase("a")){
  System.out.println("You're wrong! Try Again."); 
  userChoice = myScanner.nextLine();
}
System.out.println("You're right!");

(Remember, we need to take a new input after he got it wrong the previous time!)

public static void main(String[] args) 
{
    Scanner myScanner = new Scanner(System.in);

    System.out.println("What color is the sky?");
    System.out.println("A. Blue");
    System.out.println("B. Green");
    System.out.println("C. Yellow");
    System.out.println("D. Red");

    while(true) // Infinite loop
    {
          String userChoice = myScanner.nextLine();

          if (userChoice.equalsIgnoreCase("a"))
          {
              System.out.println("You're right!");
              break; // If user was correct, exit program
          } 
          else
          {
              System.out.println("You're wrong! Try Again.");
          }
    }
}

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