问题描述
我遇到一些代码问题。这段代码的目的仅仅是获取用户输入的数字,将它们附加到字符串上,并创建一个直方图,表示从1到50的每5个数字范围内的数字量。例如。
1 - 5: ***
6 - 10: ********
11 - 15: *
etc.
代码如下:
public class Ch10Ex4 {
public static int number;
public static ArrayList<Integer> numbers = new ArrayList<>();
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
getNums(1,50);
}
histogram(1,50,5);
System.out.println();
}
public static void getNums(int low_num,int high_num) {
Scanner sc = new Scanner(system.in);
do {
System.out.print("Enter a number between " + low_num +
" and " + high_num + ": ");
number = sc.nextInt();
} while (number < 1 || number > 50);
System.out.println(number + " has been added sucsessfully.");
numbers.add(number);
}
public static void histogram(int low,int high,int range) {
int temp_low = low;
int temp_high = low + (range - 1);
for (int i = 0; i < high / range; i++) {
System.out.print("\n" + temp_low + " - " + temp_high + ": ");
for (int arr:numbers) {
if (arr >= temp_low && i <= temp_high) {
System.out.print("*");
} else {
}
}
temp_low += range;
temp_high += range;
}
}
}
我有此代码的先前版本,我将使用两个参数来调用histogram()
。它们将是通常的最低编号和最高编号,但没有int range
参数。而且我没有最外层的for循环。我将不得不打电话给直方图10次。
histogram(1,5);
histogram(6,10);
histogram(11,15);
etc.
基本上,我会为每五个数字集来称呼它。它可以工作,但是效率极低,并且不易重用。问题是当我运行此代码(输入数字1-10)时,我得到了:
1 - 5: **********
6 - 10: *****
11 - 15:
16 - 20:
etc.
很长的帖子,很抱歉。感谢您的任何帮助,并在此先感谢您。
解决方法
错误是您在此if语句中使用i
。
if (arr >= temp_low && i <= temp_high) {
System.out.print("*");
} else {
}
将其切换为arr
,您应该会很好。