0

乱数が生成された後、スロットのインデックスと等しい値を含む配列内のスロットの数を返し、配列の各要素を別の行に出力するプログラムを作成しようとしています。アスタリスク。(このように見えるとします:)

Enter the array size: 4
a[0] = 2
a[1] = 1 *
a[2] = 0
a[3] = 2
There are 1 slots where the index is the same as the value.

しかし、私は惨めに失敗しています。正しい方向への微調整は大歓迎です。これは私がこれまでに持っているものです:

import java.util.Scanner;

public class RandomArray {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

            int i;
    System.out.println("Enter the array size: ");
            i = in.nextInt();

}

/**
 * Fills an array with random integers in the range from zero to one less
 * than the array size.
 * 
 * @param array
 *            the array to fill with random integers
 */
public static void fillArrayWithRandomInts(int array[]) {
    java.util.Random random = new java.util.Random(13);
    for (int i = 0; i < array.length; ++i)
        array[i] = (int) (random.nextDouble() * array.length);
}

public static int countSlotsWithIndexEqualToValue(int array[]) {

    int[] value = new int[13];

    for (int i = 0; i < array.length; i++) {

        if (value[13] == array[13])
            ;

    }
    return value[13];

}

public static void printArray(int array[]) {

}

}
4

3 に答える 3

2

小切手と印刷を同じ方法で組み合わせる必要があります。また、そのような組み合わせがいくつあるかをカウントする必要がある場合は、カウンターを追加する必要があります。

public static void countSlotsAndPrint(int[] a) {
    int counter = 0;
    for (int i = 0; i < a.length; i++) {
        System.out.print("a[" + i + "] = " + a[i]); // print the array as per required
        if (i == array[i]){
            System.out.println(" *"); // if index is equal to the value, then print the *            
            counter++;
        } else {
            System.out.println(); // blank line to go to the next line
        }
    }
    System.out.println("There are " + counter + " slots where the index is the same as the value.");
}
于 2013-11-08T07:31:10.723 に答える