我如何占据第二列的百分比?

时间:2014-01-31 05:12:59

标签: java object printf dice

首先,这是我的输出。

  run:
  How many dice do you want to roll: 8

 How many sides on die number 1: 5
 How many sides on die number 2: 3
 How many sides on die number 3: 7
 How many sides on die number 4: 8
 How many sides on die number 5: 5
 How many sides on die number 6: 3
 How many sides on die number 7: 5
 How many sides on die number 8: 6

 How many times do you want to roll: 50

 Results

 [8]     0 
 [9]     0 
 [10]    0 
 [11]    0 
 [12]    0 
 [13]    0 
 [14]    1 
 [15]    0 
 [16]    1 
 [17]    0 
 [18]    1 
 [19]    6 
 [20]    2 
 [21]    3 
 [22]    4 
 [23]    4 
 [24]    6 
 [25]    6 
 [26]    3 
 [27]    3 
 [28]    1 
 [29]    6 
 [30]    1 
 [31]    1 
 [32]    0 
 [33]    0 
 [34]    1 
 [35]    0 
 [36]    0 
 [37]    0 
 [38]    0 
 [39]    0 
 [40]    0 
 [41]    0 
  BUILD SUCCESSFUL (total time: 13 seconds)

参见-----------------------------------------

我正在尝试添加第3列,显示第2列的百分比,并带有实际的%符号。


我使用printf作为我的代码,但我不知道我是否可以操纵第二个%d成为百分比

  for (int i = minRoll; i < maxRoll; i++) {

        System.out.printf("[%d] \t %d \n", i , sumArray[i]);
    }

1 个答案:

答案 0 :(得分:0)

使用hashMap存储每个值的出现次数:

// initialize
Map<Integer, Integer> occ = new HashMap<Integer, Integer>();
for (int i = 1; i <= 6; i++) {
    occ.put(i,0);
}

然后,每当你“掷骰子时,请说dice = 5你做:

occ.put(dice, occ.get(dice)+1); // update the number of occurrences of the result of the current roll 

现在找到百分比将很容易,对于每个“滚动”它将是:

100 * occ.get(dice) / number-of-rolls