微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我需要一些帮助来诊断此代码的问题

如何解决我需要一些帮助来诊断此代码的问题

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。