我正在尝试创建一个连续掷 2 次骰子的游戏。它让用户只猜一次 2-12 之间的数字。如果该猜测与三个掷骰中的任何一个匹配,则他/她获胜,否则他/她输。我有另一个类来显示结果,并且我有一个计数器来计算它已经通过了多少次循环。如果用户猜对了,它会输出 0,否则输出 1。我猜循环只会循环一次,所以如果有人能指出我做错了什么让它循环三次(然后停止如果用户得到正确的答案)。
import javax.swing.JOptionPane;
/**
* @author Marcus
*
*/
public class Dice {
int randomDieNum1;//random number generator for dice
int randomDieNum2;//random number generator for dice
private final int MINVALUE1 = 1, //minimum die value
MAXVALUE1 = 6;//maximum die value
private final int MINVALUE2 = 1, //minimum die value
MAXVALUE2 = 6;//maximum die value
int userNum = Integer.parseInt(JOptionPane.showInputDialog(null, "Guess a number between 1-12", "Guess a Number",
JOptionPane.INFORMATION_MESSAGE));//gets user input
String result ; //results
int start = 0 ; //counter to see how many turns were taken
public Dice()
{
for (int i = 1 ; i <= 3; i++)
randomDieNum1 = ((int)(Math.random()* 100) % MAXVALUE1 + MINVALUE1);
randomDieNum2 = ((int)(Math.random()* 100) % MAXVALUE2 + MINVALUE2);
int total = randomDieNum1 + randomDieNum2;
if (randomDieNum1 + randomDieNum2 != userNum)
{
result = "You did not guess the \n number correctly";
++ start;
}
else if (randomDieNum1 + randomDieNum2 == userNum)
{
result = randomDieNum1 + "+" + randomDieNum2 + "=" + total + "\n" +
"You guessed the number correctly";
}
else
{
result = "You Did not guess the number correctly";
}
}
public String get() //used in another class to display count
{
String temp;
temp = "" + start;
return temp;
}
}
编辑 谢谢大家。在用户得到正确答案后,我添加了这两个建议并添加了一个中断来停止循环。这是它的样子:
public Dice()
{
for (int i = 1 ; i <= 3; i++)
{randomDieNum1 = ((int)(Math.random()* 100) % MAXVALUE1 + MINVALUE1);
randomDieNum2 = ((int)(Math.random()* 100) % MAXVALUE2 + MINVALUE2);
int total = randomDieNum1 + randomDieNum2;
if (randomDieNum1 + randomDieNum2 == userNum)
{result = randomDieNum1 + "+" + randomDieNum2 + "=" + total + "\n" +
"You guessed the number correctly";
++ turns; //
break; //stops the loop if condition is meet
}
else if(randomDieNum1 + randomDieNum2 != userNum)
{
result = "You did not guess the \n number correctly\n\n";
++ turns;
}
}
}