我正在检查 3600 万次掷骰子后骰子总数的频率。我计划制作一个 arrayList,并在出现 11 个结果中的任何一个时将其用作计数系统。如何将 1 添加到列表中的一项?
int die1, die2, dicetotal;
ArrayList<Integer> results = new ArrayList<Integer>();
results.add(0); //for the 11th
for(int i = 0; i < 36000000; i++){
die1 = (int)(Math.random() * 6) + 1
die2 = (int)(Math.random() * 6) + 1
dicetotal = die1 + die2;
Switch (dicetotal){
case 2: results.set(0, CURRENT + 1);
...
...
...
}
最佳答案
ArrayList
对此来说有点过分了。但如果你必须的话,(未经测试的代码)
首先将数组初始化为包含 13 个元素(0 到 12),这样 IndexOutOfBoundsException
就不会弹出。它们将被初始化为零。
results = new ArrayList<Integer>(13);
然后获取元素,添加一个,然后设置它
results.set(dicetotal, results.get(dicetotal) + 1);
<小时/>
事实上,如果您事先知道数组的大小,并且在程序过程中不会改变,则应该使用 int[]
。它们比 ArrayList 更快。
// initialize
results = new int[13];
// could be new int[11]; if you put results in array elements 0 to 10.
// ...
// add to tally
results[dicetotal]++;
// or, instead, pack the array because dice roll results can only be in 2 to 12.
// Put such results in array element 0 to 10,
// by subtracting 2 to the index before putting in
results[dicetotal - 2]++;
关于java - 向 ArrayList 项目添加 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17129638/