java - 我需要一些帮助来诊断此代码的问题
问题描述
我遇到了一些代码问题。这段代码的目的只是获取用户输入的数字,将它们附加到一个字符串中,并创建一个直方图,表示从 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.
第一组五个为数组中的每个数字输出一个星号。
抱歉,这篇文章太长了。任何帮助都非常感谢,并提前感谢您。
解决方案
错误是您i
在此 if 语句中使用。
if (arr >= temp_low && i <= temp_high) {
System.out.print("*");
} else {
}
切换到它arr
,你应该很好。
推荐阅读
- go - 从 Echo 中的查询字符串中获取整数值的惯用方法是什么?
- nginx - 使用通配符将新文件添加到 rsyslogd
- javascript - 警告:无法对未安装的组件 React Native 执行 React 状态更新
- python - Python Pandas,如何对字典列表进行分组和排序
- ballerina - 如何在芭蕾舞演员中创建内部阻塞队列?
- yaml - YAML 列表的自定义数据类型
- python - 为每一列保存在 DataFrame 中的唯一值
- c++ - 如何检测将文本文件读入int数组的新行
- python - Jupyter 无法显示 LaTeX 结果
- audio - 将运动传感器和声音文件合并到谷歌助手或基于 python 的音频聊天机器人程序中是否更好?