0

この課題に取り組んで 2 日間経ちましたが、とても苦労しています。私の課題では、次のようなプログラムを作成するよう求められています。

  • ユーザーが実行を実行したい回数を尋ねます (例: 20 回のうち 3 回) (出力には、各試行間の比較が含まれている必要があります)
  • ユーザーにコインを投げる回数を尋ねます (1000 回まで投げることができます)。
  • 1 から 10 までの数字をランダムに生成し、すべての数字を配列に格納します

また、10 のうち各数字が何回出現したか、どの数字が最も多く出現したか、偶数が表で奇数が裏である場合、コインのどの面が最も多く出現したかを示す必要があります。私を助けてください、私はコードを書いてみましたが、私はとても苦労していて、時間に本当にストレスを感じています!

これが私のコードです:

import java.io.*;
import java.util.Random;

public class ColCoin
{
public static void main(String[] args) throws IOException
{
    //set variables
    String timesString;
    String run;
    int times;
    int runNum;
    int i = 0;
    int x;

    //input
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    //random object
    Random r = new Random();

    System.out.print("How many times would you like to perform a run through the flips? ");
    run = br.readLine();
    runNum = Integer.parseInt(run);

    do
    {
        //ask how many times the coin will flip
        System.out.print("Please input the amount of times you would like to flip the coin (1-1000): ");
        timesString = br.readLine();

        //convert String into an integer
        times = Integer.parseInt(timesString);

        if((times > 1000)||(times < 1))
        {
            System.out.println("ERROR! Must input an integer between 1 and 1000!");
        }
        System.out.println("You chose to flip the coin " + times + " times.");
    } while((times > 1000)||(times < 1));

    for(x=0; x <= runNum; x++)
    {
        //create array
        int flip[] = new int[times];
        int countArray[] = new int[i];

        //create a new variable
        int storeTime;

        for(storeTime = 0; storeTime < flip.length; storeTime++)
        {            
            flip[storeTime] = r.nextInt(10) + 1;
            // the line above stores a random integer between 1 and 10 within the current index
            System.out.println("Flip number " + (storeTime+1) + " = " + flip[storeTime]);
        }


        //display the counts
        for(i=0; i < 10; i++)
        {
            System.out.println("The occurences of each of the numbers is: ");
            System.out.println((i+1) + " appears " + countArray[i] + "times.");
        }
    }
}
}

また、64 行目で ArrayIndexOutOfBoundsException エラーが発生しましたが、その理由はわかりません。

System.out.println((i+1) + " appears " + countArray[i] + "times.");

前もって感謝します!

4

3 に答える 3

2

問題はここにあります:

int countArray[] = new int[i];

このコードでは、0 から i-1 までのインデックスが付けられた i 個の要素を持つ配列を作成します。しかし、あなたの場合、intはまだ0です。したがって、配列の次元はゼロです(また、その配列を使用して何かを入力することはないようです)

System.out.println((i+1) + " appears " + countArray[i] + "times.");

ここでは、配列に要素 i!=0 を指定するように要求していますが、配列の次元が 0 であるため明らかにできません。

于 2013-08-25T11:50:56.607 に答える
1

問題はこの部分

int countArray[] = 新しい int[i];

この配列の作成時点では i はゼロであるため、実際には配列が満たされることはなく、常に空です。

于 2013-08-25T13:11:43.050 に答える
0

配列で動的な長さを使用していますが、固定長を使用している出力を表示するために作成したループ (下の行)。

for(i=0; i < 10; i++)

于 2013-08-25T12:24:31.000 に答える