【发布时间】:2015-04-27 03:40:15
【问题描述】:
我正在从文本文件中读取整数值,并将它们存储在 10 个 ex、1-10,11-20 的组中,就像这样存储在一个数组中。我需要在一行中打印一个星号,表示每组中有多少个数字:
1-10 *******
11-20************
我已经编写了所有代码,但无法正确打印输出。我尝试使用嵌套的 for 循环,但运气不佳。
public class Main {
public static void main(String[] args) throws FileNotFoundException {
int fileInts;
Scanner scan = new Scanner(new File("Histogram.txt"));
int[] count = new int[10];
// while loop
while (scan.hasNext()) {
// find next line
String num = scan.next();
fileInts = Integer.parseInt(num);
if (fileInts > 0 && fileInts < 11) {
count[0]++;
} else if (fileInts > 10 && fileInts < 21) {
count[1]++;
} else if (fileInts > 20 && fileInts < 31) {
count[2]++;
} else if (fileInts > 30 && fileInts < 41) {
count[3]++;
} else if (fileInts > 40 && fileInts < 51) {
count[4]++;
} else if (fileInts > 50 && fileInts < 61) {
count[5]++;
} else if (fileInts > 60 && fileInts < 71) {
count[6]++;
} else if (fileInts > 70 && fileInts < 81) {
count[7]++;
} else if (fileInts > 80 && fileInts < 91) {
count[8]++;
} else if (fileInts > 90 && fileInts < 101) {
count[9]++;
}
}
for (int s : count) {
{
for (int c = 0; c < count[c]; c++) {
System.out.print("*");
System.out.println();
s++;
}
}
//System.out.println(count[]);
}
}
}
【问题讨论】:
-
既然你要实现直方图,为什么在内部循环中调用
System.out.println()? -
我补充说,下一组星星将位于不同的行