0

前回の質問はこれと似ていましたが、最終目標について言及していませんでした。

このコードでは、サイコロが 1 つあり、4 の目が出る回数を出力します。ここで、両方とも 6 面体のサイコロが 2 つある場合、両方が 2 を振って足すと 4 になる回数を知りたいと思います。

ただし、この割り当てでは必須であるため、配列を使用する必要があります。ステートメントに別の例外を追加しようとしifましたが、プログラムで実際に配列を使用する必要があることに気づき続けています。サイコロは 1000 回転がさなければならないので、1000 個の配列を保存する必要があります。

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 つのサイコロに対して妥当な答えを生成します。たとえば、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 に答える