【问题标题】:I need some help diagnosing the problem with this code我需要一些帮助来诊断此代码的问题
【发布时间】:2020-10-19 19:59:34
【问题描述】:

我遇到了一些代码问题。这段代码的目的只是获取用户输入的数字,将它们附加到一个字符串中,并创建一个直方图,表示从 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.

第一组五个为数组中的每个数字输出一个星号。

抱歉,帖子太长了。非常感谢您的任何帮助,并提前感谢您。

【问题讨论】:

    标签: java for-loop foreach syntax logic


    【解决方案1】:

    错误是你在这个 if 语句中使用了i

    if (arr >= temp_low && i <= temp_high) {
        System.out.print("*");
    } else {
    }
    

    将它切换到arr,你应该会很好。

    【讨论】:

    • 啊,是的。我几分钟前才发现这个。太不幸了。感谢您的回答。
    猜你喜欢
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2022-11-22
    相关资源
    最近更新 更多