2

今天我在搞乱,我试图创建一个多项选择测试。我做到了这一点,它的工作原理。不过我想知道,如果用户回答错误,我将如何让它重复这个问题?如果有人可以帮助我,那就太好了!谢谢!

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

        }
     } 
4

2 回答 2

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

(请记住,在他上一次输入错误后,我们需要重新输入!)

于 2013-09-29T20:33:39.550 回答
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.");
          }
    }
}
于 2013-09-29T20:31:57.447 回答