在我的程序中,我找出平均值,模式,最大值和最小值。用户可以在1-50的范围内添加任意数量的数字。现在,我想添加一个显示用户输入结果的直方图。直方图看起来应该是
1 - 5: ****
6 - 10: ******
11 - 15: **
16 - 20: **********
21 - 25: ***********
26 - 31: ********
31 - 35: ****
36 - 41: *******
41 - 45: ************
46 - 50: *****************
我不知道如何编码。现在这是我的代码,请帮忙。 import java.util.Scanner;
int amount;
System.out.println(" Enter the amount of numbers you would like to enter: ");
amount = scan.nextInt();
int [] arr = new int [amount];
int outcome = 1;
for (int i = 0; i < arr.length; i++){
System.out.println("Enter a number 1 through 50");
outcome = scan.nextInt();
arr [i] = outcome;
}
System.out.println(" ");
System.out.println( " The average is" );
System.out.println(average(arr));
System.out.println(" ");
System.out.println( " The lowest value in the array is " );
System.out.println(min(arr));
System.out.println(" ");
System.out.println( " The largest value in the array is " );
System.out.println(max(arr));
System.out.println(" ");
System.out.println( " The most freuent number in the array is " );
System.out.println(mode(arr));
System.out.println(" ");
System.out.println("");
System.out.println("");
System.out.println();graph (arr);
}
public static double average ( int [] arr) {
double sum = 0;
int value = arr.length;
for ( int i = 0; i < arr.length; i++){
sum += arr [i];
}
sum = sum / value;
return sum;
}
public static int max(int[] arr) {
int max = arr[0];
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
return max;
}
public static int min(int[] arr) {
int min = arr[0];
for(int i = 1; i < arr.length; i++)
{
if(arr[i] < min)
{
min = arr[i];
}
}
return min;
}
public static int mode ( int[] arr) {
int mode = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] == mode) {
mode=arr[i];
}
}
return mode;
}
public static void graph (int[] arr) {
int count = 0;
System.out.print("1-5: ");
for (int i = 0; i < arr.length; i++) {
count = arr [i] ++;
if (arr[i] > 0 && arr[i] <= 5){
System.out.print("*");
}
if (arr[i] > 5 && arr[i] <= 10){
System.out.print("*");
}
}
}
}
答案 0 :(得分:1)
一种方法是使用其键对应于数值范围的地图。您只需迭代一次值数组就可以轻松填充此地图:
public static void graph (int[] arr) {
Map<Integer, Integer> map = new TreeMap<>();
for (int i=0; i < arr.length; ++i) {
int value = (arr[i] - 1) / 5;
Integer val = map.get(value);
map.put(value, val == null ? 1 : val.intValue() + 1);
}
// now iterate the map and print the histogram
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
Integer key = entry.getKey();
Integer value = entry.getValue();
System.out.print((key*5 + 1) + " - " + (key*5 + 5) + ": ");
for (int i=0; i < value; ++i) {
System.out.print("*");
}
System.out.println();
}
}