我正在尝试编写Rolling Dice程序。 10次后如何停止循环?
它需要返回计算机获胜,用户获胜还是平局的次数。
当循环结束时,我如何打印谁赢得了总冠军?
public static void main(String[] args)
{
int die1=(int)(Math.random()*6+1);
int die2=(int)(Math.random()*6+1);
int comp_wins = 0;
int user_wins = 0;
int tie = 0;
int count = comp_wins + user_wins + tie;
while (count < 11)
{
if (die1 > die2)
{
comp_wins++;
System.out.println ("Computer Wins: " + comp_wins);
}
if (die2 > die1)
{
user_wins++;
System.out.println ("User Wins: " + user_wins);
}
else
tie++;
System.out.println ("Ties: " + tie);
}
System.out.println ("The" + "wins overall!");
}
答案 0 :(得分:0)
您快到了。您只需要掷骰子并在count
循环内而不是之前增加while
。
要显示谁获胜,可以在comp_wins
语句中比较computer_wins
和if
。
更新我的答案:
您在for
循环之前设置die1和die2的值:这就是为什么同一玩家每次都获胜的原因。实际上,您要掷骰子一次,然后检查骰子十次。 (尝试通过在System.out.println(die1 + " " + die2);
循环中添加for
来为自己进行验证;这是调试自己的代码的有用方法。)
您只需要将“骰子滚动”移动到for
循环中即可:
public static void main(String[] args) {
final int MAXSTOPCOUNT = 10;
int comp_wins = 0;
int user_wins = 0;
int tie = 0;
for (int i = 0; i < MAXSTOPCOUNT; i++) {
int die1 = (int) (Math.random() * 6 + 1);
int die2 = (int) (Math.random() * 6 + 1);
if (die1 > die2) {
comp_wins++;
System.out.println("Computer Wins: " + comp_wins);
} else if (die1 < die2) {
user_wins++;
System.out.println("User Wins: " + user_wins);
} else {
tie++;
System.out.println("Ties: " + tie);
}
}
if (comp_wins > user_wins)
System.out.println("The computer wins overall!");
else
System.out.println("The user wins overall!");
}