[英]Repeating after wrong answer
今天,我四处乱逛,试图创建一个多项选择测试。 我到此为止,并且有效。 但是我在想,如果用户得到错误的答案,我该如何重复这个问题? 如果有人可以帮助我,那就太好了! 谢谢!
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.");
}
}
在这种情况下,您可以使用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!");
(请记住,他上次输入错误后,我们需要重新输入!)
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.