2015-11-13 46 views
-3
canner Input = new Scanner(System.in); 

int userNum; 


int computerNum = (int) (0 + Math.random() * 3); 

System.out.println("Let's play rock paper scissors."); 
System.out.println("Choose rock paper or scissors"); 

boolean input = false; 

String userInput = Input.nextLine(); 

do { 
switch (userInput.toLowerCase().trim()) { 
    case "rock": 
     userNum = 0; 
     input = true; 
     break; 
    case "paper": 
     userNum = 1; 
     input = true; 
     break; 
    case "scissors:": 
     userNum = 2; 
     input = true; 
     break; 
    default: 
     System.out.println("Please retry and make sure spelling is correct"); 
     input = false; 
     break; 
} 
} while (input = false); 
+1

有什麼不對?期望的行爲是什麼?您可能想閱讀[我如何提出一個好問題](http://stackoverflow.com/help/how-to-ask),這會增加獲得有用答案的可能性_drastically_。你可能會發現[ESR](https://en.m.wikipedia.org/wiki/Eric_S._Raymond)的優秀論文[如何提問智能方式](http://catb.org/~esr/) faqs/smart-questions.html)也很有幫助。 –

+0

循環...........? –

回答

2

我該如何重複一次switch語句?

籠統的回答:你把循環周圍。

在這種情況下,問題是,你已經在循環中的錯誤。

具體來說:

} while (input = false); 

分配falseinput。分配input = false的價值false ...所以你的循環語句一次執行循環體。

它應該是這樣的:

} while (input == false); 

或者更好的:

} while (!input); 

1 - 這是因爲當你使用==來測試一個布爾更好,有是,你會意外地使用=,而不是...通過上面的後果的危險!請注意,在Java中,此問題僅適用於boolean測試。對於其他類型,x = y都會有不同的類型x == y,是足以導致編譯錯誤......這是一件好事,在這方面的錯誤。