0

我之前的问题与此类似,只是我没有提到我的最终目标,

在这段代码中,我有一个骰子,我打印出它掷出 4 的次数。现在我想知道我是否有两个骰子,都是 6 面的,两个骰子会掷出多少次 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]; 
}
}
}
4

1 回答 1

1

您的示例为两个总和为 4 的骰子产生了合理的答案。我怀疑您应该创建一个数组,该数组可以保存总和在 2 到 12 之间的任何对的总和,例如:

int[] counts = new int[13];

if那么你的循环中就不需要语句了;您可以只增加该总和的计数,例如:

counts[sum]++;

可以帮助您确定您的其他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();
于 2013-03-20T03:18:46.963 回答