【发布时间】:2020-07-30 12:35:16
【问题描述】:
所以我基本上是在尝试编写一个程序,在其中输入一组由空格分隔的数字,
10 20 30 40 50 60 70 80 90 11 22 33 44 55 66 77 88 99 1 31 31 45 98 99 100 500,
当我超过 100 时,程序会根据它们所在的十个范围(1-10、11-20 等)绘制星号
但是,int 10 没有绘制在我的直方图上。我已经玩弄和修改了小于或等于,以 int 等开头的不同索引,等等,但我认为问题根源于我的 getData(int[] someArray) 方法,但我不确定是什么。
代码:
public class DistributionChart1 {
public static void main(String[] args) {
int size = 10;
int[] ranges = new int[size]; // each entry represents a range of values
getData(ranges); // pass the entire array into the method
displayChart(ranges);
System.out.println("\nSee you later!!");
} // end of main
public static void getData(int[] someArray) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a series of numbers between 1 and 100. Separate each number with a space.");
System.out.println("Signal the end by entering a number outside " + "of that range and then press enter.");
System.out.print("Go: ");
// reads an arbitrary number of integers that are in the range 1 to 100
int n;
while (scan.hasNext()) {
n = scan.nextInt();
if (n > 100) {
break;
}
int index = n / 10;
if (index == 10) {
index -= index;
break;
}
// for each integer read in, determine which range it is in and increment the
// corresponding element in the array
someArray[index] += 1;
}
scan.close();
}// end of getData
public static void displayChart(int[] someArray) {
// Print chart title with your name
System.out.println("\nDistribution Chart By simonshampoo" + "\n===================================");
// Print histogram.
for (int i = 0; i < 10; i++) {
int beginning = i * 10 + 1;
int ending = beginning + 9;
System.out.print(beginning + "-" + ending + "\t|");
for (int j = 0; j < someArray[i]; j++) {
System.out.print("*");
}
System.out.println();
}
} //
输出:
Enter a series of numbers between 1 and 100. Separate each number with a space.
Signal the end by entering a number outside of that range and then press enter.
Go: 10 20 30 40 50 60 70 80 90 11 22 33 44 55 66 77 88 99 1 31 31 45 98 99 100 500
Distribution Chart By simonshampoo
===================================
1-10 |*
11-20 |**
21-30 |**
31-40 |****
41-50 |***
51-60 |**
61-70 |**
71-80 |**
81-90 |**
91-100 |****
See you later!!
我有 10 和 1,都在 1-10 的范围内,但是我从集合中删除了 1 并且没有出现星号,所以肯定是 10。非常感谢您
【问题讨论】:
-
index -= index;?为什么不index = 0;?为什么要这样做?
标签: java arrays loops methods histogram