【发布时间】:2014-04-26 04:10:20
【问题描述】:
我必须对给定数组做一个直方图,数组中数字的频率应该用*标记。
我的程序有效,问题是如果数组中有负数,则数组排序不正确。
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);
}
}
负数应排在正数之前。无法上传图片。无论如何,感谢您的帮助。
【问题讨论】:
标签: java arrays histogram sorted