我必须制作一个给定数组的直方图,数组中数字出现的频率应该用 * 标记。
我的程序可以运行,问题是如果数组中有负数,则数组排序不正确。
public class Histogram {
//number in the counter is shown as *
private static String convertToStars(int num){
StringBuilder builder = new StringBuilder();
for(int j = 0; j < num; j++){
builder.append('*');
}
return builder.toString();
}
public static void outputHistogram(Integer[] array) {
//if array is empty
if(array.length == 0){
System.out.println("Keine Elemente vorhanden.");
return;
}
//array is cloned, so it is possible to delete same numbers
Integer[] copy = array.clone();
Arrays.sort(copy);
System.out.println(Arrays.toString(copy) + "\n");
for(int i = 0; i < copy.length; i++){
int counter = 1;
for(int j = 0; j < copy.length; j++){
if(i != j && array[i] == array[j]){
counter++;
copy[j] = null;
}
}
if(copy[i] != null){
System.out.println("\t" + array[i] + "\t" + convertToStars(counter));
}
}
}
public static void main(String[] args) {
Integer[] array = {2, 4, 23, 23, 23, 2, -8, 56, 4, 2};
Histogram h = new Histogram();
System.out.println("Histogramm des Arrays: " );
h.outputHistogram(array);
}
负数应该排在正数之前。无法上传图像。无论如何,感谢您的帮助。
最佳答案
您似乎在嵌套循环中互换了 array
和 copy
的用法。
您保留原位排序的副本
用于打印目的并操作您的原始数组
和控制变量,否则您将丢失原位排序数组的信息。
for (int j = 0; j < copy.length; j++) {
if (i != j && copy[i] == copy[j]) {
counter++;
array[j] = null;
}
}
if (array[i] != null) {
System.out.println("\t" + copy[i] + "\t"
+ convertToStars(counter));
}
给出正确的输出,
Histogramm des Arrays:
[-8, 2, 2, 2, 4, 4, 23, 23, 23, 56]
-8 *
2 ***
4 **
23 ***
56 *
关于java - 排序数组的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22513924/