【发布时间】:2017-01-08 21:17:23
【问题描述】:
我的程序从文件中读取任意数量的整数,然后为 1 到 100 之间的所有整数打印直方图条形图。
该代码有效,我已经尝试使用所有可能的格式使其更短,但后来我的代码停止工作。所以这个长版本是目前唯一有效的版本。
所以我的问题只是出于好奇,如果我的 if 语句和直方图的打印有更短的方法。
注意:并非文件中的所有整数都必须在 [1-100] 区间内
Create an object representing a file
File file = new File("path");
Scanner fileScan = new Scanner(file);
ArrayList<Integer> list = new ArrayList<Integer>();
int total=0;
while (fileScan.hasNext()){
total++;
list.add(fileScan.nextInt());
}
int [] counter = new int [10];
for(int i=0; i<list.size();i++){
if (list.get(i) >=1 && list.get(i)<=10){
counter[0]++;
}
if (list.get(i) >10 && list.get(i)<=20){
counter[1]++;
}
if (list.get(i) >20 && list.get(i)<=30){
counter[2]++;
}
if (list.get(i) >30 && list.get(i)<=40){
counter[3]++;
}
if (list.get(i) >40 && list.get(i)<=50){
counter[4]++;
}
if (list.get(i) >50 && list.get(i)<=60){
counter[5]++;
}
if (list.get(i) >60 && list.get(i)<=70){
counter[6]++;
}
if (list.get(i) >70 && list.get(i)<=80){
counter[7]++;
}
if (list.get(i) >80 && list.get(i)<=90){
counter[8]++;
}
if (list.get(i) >90 && list.get(i)<=100){
counter[9]++;
}
}
int valueTotal=0;
for (int j=0; j<counter.length; j++){
valueTotal += counter[j];
}
System.out.print("Reading integers from file: "+file);
System.out.print("\nNumber of integers in the interval [1,100]: "+valueTotal);
System.out.print("\nOthers: "+(total-valueTotal));
System.out.print("\nHistogram\n");
System.out.print("1 - 10 | ");
display(counter[0]);
System.out.print("\n11 - 20 | ");
display(counter[1]);
System.out.print("\n21 - 30 | ");
display(counter[2]);
System.out.print("\n31 - 40 | ");
display(counter[3]);
System.out.print("\n41 - 50 | ");
display(counter[4]);
System.out.print("\n51 - 60 | ");
display(counter[5]);
System.out.print("\n61 - 70 | ");
display(counter[6]);
System.out.print("\n71 - 80 | ");
display(counter[7]);
System.out.print("\n81 - 90 | ");
display(counter[8]);
System.out.print("\n91 - 100| ");
display(counter[9]);
}
public static void display(int n){
for (int i=0; i<n; i++){
System.out.print("*");
}
}
}
我的输出:
Reading integers from file: ....txt
Number of integers in the interval [1,100]: 18
Others: 4
Histogram
1 - 10 | ******
11 - 20 | *
21 - 30 | ***
31 - 40 |
41 - 50 | *
51 - 60 | *
61 - 70 | *
71 - 80 | ***
81 - 90 | *
91 - 100| *
【问题讨论】:
-
您必须始终在两端为超出范围的值设置 bin(
counter元素),除非您可以保证 bin 计算不会产生超出范围的 bin 编号。