我使用以下代码创建了一个直方图:
import java.util.*;
public class Murray_A03Q3 {
public static void main (String [] args){
int num = 1;
int[] nums = new int[10];
List<Integer> list = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
while(num != 0){
System.out.print("Enter a value to plot: ");
num = scan.nextInt();
System.out.println();
if(num != 0)
list.add(num);
}
for (int a = 0; a < list.size(); a++){
nums[(list.get(a)-1) / 10]++;
}
for (int count = 0; count < 10; count++){
System.out.print((count*1+1) + (count == 1 ? " ": " ") + "| \t");
for(int h = 0; h < nums[count]; h++)
System.out.print("#");
System.out.println();
}
} // end of main
} // end of class Murray
输出为:
1 | ######
2 |
3 |
4 |
5 |
6 | #
7 |
8 |
9 | #
10 |
但我需要它来打印用户输入的值,从 1-10 而不是 1-100,就像它似乎正在打印一样(上面的输出使用了 10 个之外的两个值,这就是为什么在 6 和 9 处打印了一个) .我浏览了代码并尝试以不同的方式操纵它以实际获得我想要的东西,但我无法弄清楚。我的问题是,实际需要更改什么才能获得 1-10 之间的值?
感谢您的帮助!
最佳答案
你应该限制它,所以他们只能输入 1-10。在您的 nums 数组中,我只存储了该索引号的出现次数。然后在打印时,只需打印索引+1,内部循环会为您执行#。
import java.util.*;
public class Murray_A03Q3{
public static void main (String [] args){
int num = 1;
int[] nums = new int[10];
List<Integer> list = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
while(num != 0){
System.out.print("Enter a value to plot: ");
num = scan.nextInt();
System.out.println();
if(num > 0 && num <= 10)
list.add(num);
if(num > 10 || num < 0)
System.out.println("Please enter a number 1-10");
}
for (int a = 0; a < list.size(); a++){
nums[a] = Collections.frequency(list, a);
}
for (int count = 0; count < 10; count++){
System.out.print((count+1) + "\t|");
for(int h = 0; h < nums[count]; h++)
System.out.print("#");
System.out.println();
}
} // end of main
} // end of class Murray
我还移动了选项卡前面的线,使它看起来更均匀。这是 1、2、3 的输入。它用于在第 1 行显示所有 3 个#。
1 |#
2 |#
3 |#
4 |#
5 |
6 |
7 |
8 |
9 |
10 |
关于java - 在 Java 中创建直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31496984/