3 回答
TA贡献1816条经验 获得超6个赞
这是另一个使用流的答案
public static void main(String[] args){
Random rng = new Random();
long result = IntStream
.generate(() -> rng.nextInt(6) + rng.nextInt(6) + 2)
.limit(100)
.filter(x -> x == 7)
.count();
System.out.println("Total number of time sum equaled 7 was " + result);
}
TA贡献1820条经验 获得超9个赞
使用 Java 8,程序将如下所示:
public class Dice
{
static int count = 0;
static Random ran = new Random();
public static void main(String[] args)
{
IntStream.rangeClosed(1, 100). // iterates 1 to 100
parallel().// converts to parallel stream
forEach(i -> {
rollDiceAndCheckIfSumIs7();
});// prints to the console
System.out.println("Out of 100 times, total number of times, sum was 7 is :" + count);
}
private static void rollDiceAndCheckIfSumIs7()
{
int dice1 = ran.nextInt(7);
int dice2 = ran.nextInt(7);
count += (dice1 + dice2 == 7) ? 1 : 0;
}
}
TA贡献1775条经验 获得超8个赞
只需将您的替换for (int count = 0; count++) { ... }为if (sum==7) count++并将其放在后面int sum = (dice1 + dice2);
如果在 100 个双掷骰子的循环中总和为 7,则这会增加计数。
要删除错误的骰子范围(0-7,请参阅评论@Robby Cornelissen)只需执行randomGenerator.nextInt(6)+1.
int count = 0; // No. of rolls = to 7
for (int i = 0; i <= 100; i++){
int dice1 = randomGenerator.nextInt(6)+1;
int dice2 = randomGenerator.nextInt(6)+1;
int sum = (dice1 + dice2);
if (sum==7) count++;
System.out.println(dice1 + ", " + dice2 + ", total: " + sum + " roll: " + i);
}
System.out.println("Total number of time sum equaled 7 was " + count);
添加回答
举报