首页 > 解决方案 > 我需要一些帮助来诊断此代码的问题

问题描述

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

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

抱歉,这篇文章太长了。任何帮助都非常感谢,并提前感谢您。

标签: javafor-loopforeachsyntaxlogic

解决方案


错误是您i在此 if 语句中使用。

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

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


推荐阅读