我之前的问题与此类似,只是我没有提到我的结束目标,
在这段代码中我有一个骰子,我打印出它滚动的次数4.现在我想知道我是否有两个骰子,都是六面,两次都会滚动2次因此增加到4.
但是,我需要使用数组,因为它在此赋值中是必需的。我已经尝试在if
语句中添加另一个异常,除了我一直意识到我需要在程序中实际使用数组。应存储1000个阵列,因为骰子必须滚动1000次,因此检查它从卷筒中添加到4的次数,然后打印次数。
import java.io.*;
public class dont {
public static void main(String[] args) throws Exception {
// System.out.println(input());
int[] counts = new int[13];
System.out.print("The number of times it rolls 4 on two 6 sided dice :" + counts);
}
public static int input () throws IOException {
BufferedReader myInput = new BufferedReader (new InputStreamReader
System.out.println("Hello and welcome to the program");
System.out.println("In this program two six sided dices will be rolled and one eleven
sided dice will be rolled (1000 times each");
int sum;
int[] counts = new int[13];
System.out.println("The dices will be rolled to determine the odds of how many times the roll 2 comes up on both dies(Press any key to con't) ");
myInput.readLine();
//int count2=0;
int Sixside;
for (int i = 0; i < 1000; i++)
{
// two dice that add to 4, after being rolled one thousand times
Sixside = (int)(Math.random ()*6+1)+(int)(Math.random ()*6+1) == 4;
//print the number of times they add to 4
counts[sum]++;
}
counts[i] = Sixside;
{
//return array to main
return counts [13];
}
}
}
答案 0 :(得分:1)
你的例子为两个总和为4的骰子产生合理的答案。我怀疑你应该创建一个数组,它可以保存任何对的总和,其总和在2到12之间,例如:
int[] counts = new int[13];
然后你的循环中不需要if
语句;你只需增加该总和的计数,例如:
counts[sum]++;
此table可以帮助您确定您的其他counts
是否合理。
附录:这是您方法的简化版本:
public static int[] input() {
int[] counts = new int[13];
for (int i = 0; i < 1000; i++) {
int sum = // your expression for the sum of two dice
counts[sum]++;
}
return counts;
}
您可以这样称呼它并检查任何特定的总数,例如counts[4]
。
int[] counts = input();