2

私は9月末から、Javaを主言語とする修士課程ソフトウェア開発変換コースを受講しています。私たちは最初に実際的な到来を評価しました、そして私はいくつかのガイダンスを望んでいました。

乱数ジェネレーターによって生成された100個の整数(すべて1〜10)を格納する配列を作成し、この配列の10個の数値を1行に出力する必要があります。2番目の部分では、これらの整数をスキャンし、各数値が表示される頻度をカウントして、結果を2番目の配列に格納する必要があります。

最初のビットは大丈夫ですが、2番目のビットの実行方法について混乱しています。スキャナークラスを調べて、使用できるメソッドがあるかどうかを確認しましたが、見つかりません。誰かが私を正しい方向に向けることができますか?答えではなく、おそらくそれがどのライブラリから来ているのでしょうか?

これまでのコード:

import java.util.Random;

public class Practical4_Assessed 
{

public static void main(String[] args) 
{

    Random numberGenerator = new Random ();

    int[] arrayOfGenerator = new int[100];

    for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++)
        arrayOfGenerator[countOfGenerator] = numberGenerator.nextInt(10);

    int countOfNumbersOnLine = 0;
    for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
    {
        if (countOfNumbersOnLine == 10)
        {
            System.out.println("");
            countOfNumbersOnLine = 0;
            countOfOutput--;
        }
        else
        {
            System.out.print(arrayOfGenerator[countOfOutput] + " ");
            countOfNumbersOnLine++;
        }
    }
  }
}

ありがとう、アンドリュー

4

2 に答える 2

1

ライブラリは必要ありません。配列をループしてカウントするだけです。

    for (int x : arrayOfGenerator)
        ar2[x]++;

    //test with
    for (int i=0; i<ar2.length; i++)
        System.out.println("num of "+i+" ="+ar2[i]);
于 2012-10-27T11:05:42.563 に答える
1

乱数を取得するたびに、それをint変数に格納してから、「カウント配列」の対応するバケットをインクリメントします。

int[] countingArray = new int[10];
for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++) {
    // Get a number between 0 and 9 (inclusive); we'll add 1 to it in a moment
    int number = numberGenerator.nextInt(10);

    // Update your counts (array indexes start at 0, which is why we
    // haven't added to `number` yet)
    countingArray[number]++;

    // Store the actual number, which we add to because the assignment
    // is for 1-10, not 0-9
    arrayOfGenerator[countOfGenerator] = number + 1;
}

さて、countingArray[0]1あなたが持っcountingArray[1]ている数、あなたが持っている数2などです。例えば、x1から10まではあなたが持っているcountingArray[x - 1]xです。

于 2012-10-27T11:06:26.170 に答える