我必须使程序掷2个骰子100次,并计算总和等于7的时间。
我尝试做一个for count循环来计算总和= 7,但我认为我在逻辑上偏离了基础。
// int i = 0; No. of rolls
// int count = 0; No. of rolls = to 7
for (int i = 0; i <= 100; i++){
int dice1 = randomGenerator.nextInt(7);
int dice2 = randomGenerator.nextInt(7);
int sum = (dice1 + dice2);
System.out.println(dice1 + ", " + dice2 + ", total: " + sum + " roll: " + i);
}
for (int count = 0; count++) {
System.out.println(count);
}
System.out.println("Total number of time sum equaled 7 was " + count);
我正确地获得了随机掷骰,掷骰数和骰子总和,只需要弄清楚如何添加总和= 7个计数,我就会陷入困境。
答案 0 :(得分:1)
这是使用流的另一个答案
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);
}
答案 1 :(得分:0)
只需将您的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);
答案 2 :(得分:0)
使用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;
}
}