2013-09-29 34 views
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."); 

     } 
    } 
+5

使用循環;而不是在Stack Overflow上發佈這個問題,你應該在線閱讀教程或閱讀關於java的書。 – u8sand

+0

'while(1)'。發瘋。 – GGrec

+1

@GGrec這在Java中不起作用,它必須是'while(true)'。 –

回答

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

'while(1)'should'while(true)' –

+2

@SimonAndreForsberg哎呀,該死的C++。 – GGrec

3

您可以在此情況下,使用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!"); 

(請記住,我們需要一個新的輸入後,他聽錯了,以前的時間! )