简体   繁体   English

错误答案后重复

[英]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! 在这种情况下,您可以使用While语句! 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: 现在,将“只要”更改为“ while(...)”,我们将获得以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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