【发布时间】:2021-06-05 19:53:44
【问题描述】:
我想随时通过键入 Q 来终止程序。我不能把它放在“diceChosen”中,因为它是一个整数。我尝试了不同的方法,但对我没有任何效果。
Scanner userInput = new Scanner(System.in);
int wins = 0;
int losses = 0;
int diceOne = 0;
int diceTwo = 0;
int diceThree = 0;
int sum = 0;
System.out.println("Välkommen till spelet 12. Du ska slå 1-3 tärningar och försöka få summan 12...");
for (int counter = 0; counter < 3; counter++) {
System.out.printf("%nAnge vilken tärning du vill slå[1,2,3](avsluta med q): ");
int diceChosen = userInput.nextInt();
if (diceChosen == 1)
diceOne = (int)(Math.random() * 6) + 1;
if (diceChosen == 2)
diceTwo = (int)(Math.random() * 6) + 1;
if (diceChosen == 3)
diceThree = (int)(Math.random() * 6) + 1;
sum = diceOne + diceTwo + diceThree;
if (sum == 12)
++wins;
if (sum > 12)
++losses;
System.out.printf("%d %d %d sum: %d #vinst: %d #förlust: %d", diceOne, diceTwo, diceThree, sum, wins, losses);
}
【问题讨论】:
-
您可以使用try-catch 语句输入不匹配异常,然后创建一个if 语句来查看用户是否按下了q,然后在if 中输入
System.exit(0);。
标签: java if-statement terminate dice