gpt4 book ai didi

java - 掷骰子数组和方法调用

转载 作者:行者123 更新时间:2023-12-02 02:46:26 25 4
gpt4 key购买 nike

我正在研究这个问题,但我不知道如何获取一个数组来跟踪 main 中的滚动以及如何循环调用正在进行滚动的方法。 (请帮助我自己解决这个问题,没有老师。)

问题:

编写一个程序来模拟掷两个骰子。提示用户输入掷骰子的数量。使用循环重复调用模拟掷骰子的方法,并将两个骰子的总和返回给 main。在 main 中的数组中跟踪掷骰结果,并通过显示掷骰结果来结束程序。

示例输出:

How many times should I roll the dice? 100
Results for 100 dice rolls
2 was rolled 4 times
3 was rolled 2 times
4 was rolled 1 times
5 was rolled 8 times
6 was rolled 15 times
7 was rolled 16 times
8 was rolled 17 times
9 was rolled 18 times
10 was rolled 10 times
11 was rolled 6 times
12 was rolled 3 times

到目前为止我的代码:

import java.util.Scanner; 
public class TestingCenter {
private static Scanner input;
public static void main(String[] args){

System.out.println("How many times should I roll the dice? ");
int answer = input.nextInt();
for (int x = 0; x < answer; x++) {


}
}


public static int amount(int x){
int die1;
int die2;
int roll;
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
roll = die1 + die2;
return roll;

}
}

最佳答案

这是在 main 方法中使用 int[] 实现的:

import java.util.Random;
import java.util.Scanner;

public class TestingCenter {

private static final Random random = new Random();

public static void main(final String[] args) {

System.out.println("How many times should I roll the dice? ");
int answer = 0;
try (Scanner scanner = new Scanner(System.in)) {
answer = scanner.nextInt();
}
final int[] results = new int[11];
for (int x = 0; x < answer; x++) {
results[amount() - 2]++;
}
System.out.println(String.format("Results for %s dice rolls ", answer));
for (int i = 0; i < 11; i++) {
System.out.println(String.format("%s was rolled %s times", i + 2, results[i]));
}
}

public static int amount() {
return random.nextInt(6) + random.nextInt(6) + 2;

}
}

测试输出:

How many times should I roll the dice? 
100
Results for 100 dice rolls
2 was rolled 1 times
3 was rolled 8 times
4 was rolled 10 times
5 was rolled 12 times
6 was rolled 14 times
7 was rolled 18 times
8 was rolled 13 times
9 was rolled 12 times
10 was rolled 6 times
11 was rolled 4 times
12 was rolled 2 times

关于java - 掷骰子数组和方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44506687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com