[英]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.