【发布时间】:2014-02-28 20:27:51
【问题描述】:
好的,所以我正在尝试创建一个骰子游戏,其中 args[0] 是玩游戏的次数。游戏.... 掷两个骰子,如果总和不等于 7,则将它们的值加到总和中。如果总和等于 7,则游戏结束。我想跟踪所有游戏中最大的总和,而最小的总和应该始终为零,因为当总和等于 7 时,它会将总和设置为 0。 这是我的代码。我不认为它打印的是我想要的...帮助?还有我如何在 Eclipse 中自动格式化?
public class diceGame {
public static void main(String[] args) {
int dice1;
int dice2;
int count=0;
int theSum=0;
int lowest=500;
int finalSum=0;
int diceSum=0;
while (count !=Integer.parseInt(args[0])){
count=count+1;
theSum=0;
while(diceSum!=7){
diceSum=0;
dice1=1 + (int)(Math.random() * ((6 - 1) + 1));
dice2=1 + (int )(Math.random() * ((6 - 1) + 1));
diceSum=dice1+dice2;
if (diceSum !=7){
theSum=theSum+diceSum;
if (theSum>finalSum){
finalSum=theSum;
}
if (theSum<lowest){
lowest=theSum;
}
}
}
}
System.out.println("After "+args[0]+" simulations: ");
System.out.println("Biggest sum: "+finalSum);
System.out.println("Smallest sum: "+lowest);
}
}
我修好了
public class diceGame {
public static void main(String[] args) {
int dice1;
int dice2;
int count = 0;
int theSum = 0;
int lowest = Integer.MAX_VALUE;
int finalSum = 0;
int diceSum;
int totalSum=0;
while (count < Integer.parseInt(args[0])) {
count = count + 1;
diceSum=0;
theSum=0;
while (diceSum!=7) {
diceSum = 0;
dice1 = 1 + (int) ((Math.random() * (6 - 1)) + 1);
dice2 = 1 + (int) ((Math.random() * (6 - 1)) + 1);
diceSum = dice1 + dice2;
if (diceSum != 7) {
theSum = theSum + diceSum;
}
//System.out.println("the sum is "+theSum);
}
if (theSum > finalSum) {
finalSum = theSum;
}
if (theSum < lowest) {
lowest = theSum;
}
totalSum=totalSum+theSum;
}
double average=(double)totalSum/(Double.parseDouble(args[0]));
System.out.println("After " + args[0] + " simulations: ");
System.out.println("Biggest sum: " + finalSum);
System.out.println("Smallest sum: " + lowest);
System.out.println("The average is: "+average);
}
}
【问题讨论】:
-
这段代码在做什么?自动格式化是 ctrl+I,谷歌会比我们更快地告诉你。
-
右键单击,来源,格式。那里也有一个快捷方式。
-
theSum=theSum+diceSum;你为什么要这样做? -
另外,
((6 - 1) + 1)是 6。我认为你的括号放错地方了。使用 Random.nextInt(6) + 1 掷一个 6 面骰子。 -
可以提取
Integer.parseInt(args[0]),不用每次都计算。
标签: java if-statement random printing while-loop