我的编程课程作业。我只有一个我无法弄清楚的问题。
我的说明如下:编写一个程序,模拟玩家掷骰子100次后获胜的频率。如果玩家掷出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;
}
}
}
答案 0 :(得分:0)
我认为您不需要在代码中使用if条件。
if (sumOfDies == point) { System.out.println(sumOfDies + " You Won! Congratulations! You Won! Congratulations!"); return true; }
实际上你需要在你的代码中满足条件。
if (sumOfDies == 7 || sumOfDies == 11) { System.out.println(sumOfDies + " You Won! Congratulations! You Won! Congratulations! "); return true; }
else { System.out.println(sumOfDies + " Congratulations! You Lost! "); return false; }
这是你的功能应该如何工作:
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 {
System.out.println(sumOfDies + " Congratulations! You Lost! ");
return false;
}
}