错误回答后重复

时间:2013-09-29 20:27:31

标签: java

今天我在乱搞,我正在尝试创建一个多项选择测试。我做到了这一点,它的确有效。我想知道,如果用户得到错误的答案,我将如何重复这个问题?如果有人能帮助我,那就太棒了!谢谢!

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

        }
     } 

2 个答案:

答案 0 :(得分:4)

在这种情况下你可以使用While语句! 让我们这样看:只要用户没有正确回答,你就不会继续。现在用“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!");

(请记住,我们在上一次错误之后需要接受新的输入!)

答案 1 :(得分:0)

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