Java编码数组

时间:2015-01-20 15:48:23

标签: java arrays

我必须创建一个在执行时输入数据的数组,并显示最高值及其频率。还输入所有其他值的频率。当我输入值时,我的代码是正确的。用其他人帮助任何人?

1 个答案:

答案 0 :(得分:0)

我相信这就是你所要求的。代码本身很简单。

您也可以用最高索引替换最高的计数器......但您可以选择:)

// This is the part you already implemented...
int[] array = {10, 2, 2, 3, 5, 6, 1, 32, 123, 2, 32, 32, 32, 1, 23, 123};

// Get Highest
int highest = array[0];
int highestCounter = 1;
for (int i = 1; i < array.length; i++) {
    if (array[i] > highest) {
        highest = array[i];
        highestCounter = 1;
    } else if (array[i] == highest) {
        highestCounter++;
    }
}

System.out.println("Highest = " + highest);
System.out.println("Highest Frequencies = " + highestCounter);

// Get frequencies 
int[] freqArray = new int[array.length];
for (int i = 0; i < array.length; i++) {
    int counter = 0;
    for (int j = 0; j < freqArray.length; j++) {
        if (array[i] == array[j]) {
            counter++;
        }
    }
    freqArray[i] = counter;
}

// Finally display result
for (int i = 0; i < freqArray.length; i++) {
    System.out.println(array[i] + " = " + freqArray[i]);
}

编辑:下面的代码也是如此,但这次它存储了最高值的索引位置。此外,代码现在也被放置在函数中,如果需要再次重用它,这将真正帮助您:)

public static void main(String... args) {
    int[] array = {10,2,2,3,5,6,1,32,123,2,32,32,32,1,23,123};

    int highestIndex = getHighestIndex(array);
    int[] frequencies = createFrequencyArray(array);

    System.out.println("Highest = " + array[highestIndex]);
    System.out.println("Highest value frequency " + frequencies[highestIndex]);

    // Finally display result
    for (int i = 0; i < frequencies.length; i++) {
        System.out.println(array[i] + " frequency " + frequencies[i]);
    }

}

public static int getHighestIndex(final int[] array) {
    // Assume the highest value is at position 1
    int highestIndex = 0;

    // Ensure the array has values
    if (array.length > 0) {
        // No need to check 1 again, thus start from position 2 or array[1]
        for (int i = 1; i < array.length; i++) {
            if (array[i] > array[highestIndex]) {
                highestIndex = i;
            } 
        }
    } else {
        highestIndex = -1;
    }

    return highestIndex;
}

public static int[] createFrequencyArray(final int[] array) {
    int[] frequencies = new int[array.length];
    for (int i = 0; i < array.length; i++) {
        int counter = 0;
        for (int j = 0; j < frequencies.length; j++) {
            if (array[i] == array[j]) {
                counter++;
            }
        }
        frequencies[i] = counter;
    }

    return frequencies;
}