我编写了一个带有子类的应用程序,该子类将根据用户输入多少个边来掷骰子,并使用一个整数,该整数将掷骰子一定次数。
如:用户进入6面,并希望掷骰子1000次。
我还应该使用与我编码的数组类似的数组。
我现在拥有的:
public class DDiceRoller {
public static void diceStats() {
int maxNum = DiceRolling.diceSides;
Scanner sc = new Scanner(System.in);
int randomValue = 1 + (int) (Math.random() * maxNum);
int randomValue2 = 1 + (int) (Math.random() * maxNum);
int die1 = (randomValue);
int die2 = (randomValue2);
int sum = die1 + die2;
int rollnum;
int idx;
System.out.println("Welcome to the Dice Roll Stats Calculator!");
int[] combinations = new int[maxNum]; //I haven't even used this variable yet, don't know how.
System.out.println("Enter amount of rolls: ");
rollnum = sc.nextInt();
for (idx = 0; idx < rollnum; idx++) {
System.out.println(sum); //I know this is wrong, just don't know what to do.
}
}
}然后,计算器将根据程序运行多少次来运行程序和输出百分比。所以就像..。
所需输出:
Total Count Percentage
----- --------- ----------
2 123 3.01%
3 456 6.07%
4 etc 3.19%
5 ??? 4.45%
6 ??? 8.90%
7 ??? 8.62%
8 ??? 7.63%
9 ??? 6.92%
10 ??? 5.40%
11 ??? 6.96%
12 ??? 8.36% 当前的输出:现在所得到的只是输入返回的相同值,因为我现在使用'for‘循环所做的一切就是重复'sum',不管掷骰子多少次。和也不会为每次迭代返回不同的数字。
我的主要目标是按用户要求的任意次数掷骰子。使用Java数组存储结果。例如,每次我要执行下一卷时,创建一个新的骰子。这样,我可以将每一对骰子存储在一个数组中。
我正试着学习如何把这些代码写成几个片段,但是我现在太迷茫了,以至于我感到被打败了。对于你所能给予的任何指导,我都不胜感谢。如果这让我很困惑,我真的很抱歉,我不完全理解说明.
发布于 2017-12-11 03:11:49
您可以使用2D数组或散列映射来完成此操作,但我更喜欢2x ArraList。
NumberFormat formatter = new DecimalFormat("#0.00");
ArrayList<Integer> numbers = new ArrayList<Integer>();
ArrayList<Integer> counts = new ArrayList<Integer>();
int maxNum = DiceRolling.diceSides;
Scanner sc = new Scanner(System.in);
int rollnum;
int randomValue;
System.out.println("Welcome to the Dice Roll Stats Calculator!");
System.out.println("Enter amount of rolls: ");
rollnum = sc.nextInt();
for (int i = 0; i < rollnum; i++) {
randomValue = (1 + (int) (Math.random() * maxNum)) + (1 + (int) (Math.random() * maxNum));
if(numbers.contains(randomValue)){
int position = numbers.indexOf(randomValue);
counts.set(position, counts.get(position)+1);
}else{
numbers.add(randomValue);
counts.add(1);
}
}
System.out.println("Total\tCount\tPercentage");
System.out.println("-----\t---------\t----------");
for(int i = 0; i<numbers.size(); i++){
System.out.println(numbers.get(i) +"\t" + counts.get(i) + "\t" + formatter.format(((double)(counts.get(i)*100))/rollnum) + "%";
}这是你的答案吗?我希望这能行。
https://stackoverflow.com/questions/47745606
复制相似问题