2015-11-13 60 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,是足以导致编译错误......这是一件好事,在这方面的错误。