如何计算时间总和=7的次数？

2023-01-05 17:22:07

//    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);

3 回答

TA贡献1561条经验 获得超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贡献1575条经验 获得超9个赞

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;

}

}

www说

TA贡献1535条经验 获得超8个赞

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);

• 3 回答
• 0 关注
• 18 浏览

0/150