【发布时间】:2016-10-17 04:05:30
【问题描述】:
我的编程课程有一个作业。我只有一个问题无法解决。
我的指令如下:编写一个程序,模拟玩家掷骰子 100 次后获胜的频率。如果玩家掷出 7 或 11,他们就赢了
我的问题如下:我的程序显示我赢得的次数超出了我应得的次数。我只希望我的程序打印出用户获胜的消息,如果他们有 7 或 11,但这并没有发生。谁能给我一些关于我可能需要做什么的建议?
下面是我的代码。非常感谢您的帮助。
@author Jordan Navas
@version 1.0
COP2253 Workshop7
File Name: Craps.java
*/
import java.util.Random;
public class Craps
{
public static void main(String[] args)
{
Random rand = new Random();
int gamesWon=0;
int gamesLost=0;
for(int i=1;i<=100;i++)
{
craps(rand);
if(craps(rand))
{
gamesWon++;
}
else{
gamesLost++;
}
}
System.out.println("Games You Have Won: " + gamesWon);
System.out.println("Games You Have Lost: " + gamesLost);
}
public static boolean craps(Random rand)
{
int firstDice = rand.nextInt(6)+1;
int secondDice = rand.nextInt(6+1);
int sumOfDies = firstDice + secondDice;
System.out.print("[" + firstDice + "," + secondDice + "]");
if (sumOfDies == 7 || sumOfDies == 11)
{
System.out.println(sumOfDies + " You Won! Congratulations! You Won! Congratulations! ");
return true;
} else if(sumOfDies == 2 || sumOfDies == 3 || sumOfDies == 12)
{
System.out.println(sumOfDies + " Congratulations! You Lost! ");
return false;
}
int point = sumOfDies;
System.out.print("Point: " + point + " ");
if (sumOfDies == point)
{
System.out.println(sumOfDies + " You Won! Congratulations! You Won! Congratulations!");
return true;
} else
{
System.out.println(sumOfDies + " Congratulations! You Lost! ");
return false;
}
}
}
【问题讨论】:
-
if (sumOfDies == point)将始终返回true -
return false 不是否定了这一点吗?这还不够好吗?我应该删除那部分编码吗?
-
此代码将为
2,3 or 12以外的任何内容返回true -
您在说出
int point = sumOfDies;后立即检查if (sumOfDies == point)。你基本上是在检查一个值是否等于它自己。该检查将始终为真。 -
谢谢,我明白你在说什么。如何将 (sumOfDoes == 2) 等的 if 语句更改为除 7 或 11 之外的所有其他值。这些是唯一可以获胜的 Dies 总和。