我想得到一些我正在编写的程序的帮助。我想输出两个,两个面部频率加在一起。这是我写的当前代码。它现在非常基础,写得很差。我对Java编码很陌生,所以请给我任何有助于我的提示和技巧:)。
import java.util.Random;
public class DiceRolling {
public final static Random randomNumbers = new Random();
public static void main(String[] args) {
int[] dice1 = new int[7];
int[] dice2 = new int[7];
// prints out the headings
for (int headOne = 1; headOne <= 6; headOne++)
System.out.print(" " + headOne);
System.out.println();
for (int headTwo = 1; headTwo <= 6; headTwo++)
System.out.println(headTwo);
// The rolls of the two dices begins here
for (int frequencyOne = 0; frequencyOne < 36000000; frequencyOne++) {
++dice1[1 + randomNumbers.nextInt(6)];
}
// output faces of die
for (int faceOne = 1; faceOne < dice1.length; faceOne++) {
System.out.print(" " + dice1[faceOne]);
}
}
}
答案 0 :(得分:-1)
以下代码将打印出每张脸的滚动次数。您会注意到,由于随机java库使用的随机数算法,所有面都滚动的次数几乎相同。如果您有任何疑问,请致电!
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Random;
public class DiceRolling {
public final static Random randomNumbers = new Random();
public static void main(String[] args) {
// create a hashmap to hold the amount of times each number was rolled
HashMap<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
// roll the dice 360000 times
for (int rolls = 0; rolls < 360000; rolls++) {
// roll dice
int result = (randomNumbers.nextInt(6) + 1);
// if the result has already happened add it
if (frequencies.containsKey(result)) {
frequencies.put(result, (frequencies.get(result) + 1));
continue;
}
// else add it and set its frequency to 1
frequencies.put(result, 1);
}
// print results
for (Entry<Integer, Integer> entry : frequencies.entrySet()) {
System.out.println("Face: " + entry.getKey() + ", Times rolled: " + entry.getValue());
}
}
}