简体   繁体   中英

I need some help diagnosing the problem with this code

I'm having trouble with some code. This code's purpose is just to take user-inputted numbers, append them to a string, and create a histogram representing the amount of numbers in each 5 number range from 1 to 50. Ex.

1 - 5: ***
6 - 10: ********
11 - 15: *
etc.

Here is the code:

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;
        }
        
    }
    
}

I had a previous version of this code where I would call histogram() with two parameters. These would be the lowest number and the highest number like usual but no int range parameter. And I didn't have the outermost for-loop. I would have to call histogram 10 times ex.

histogram(1, 5);
histogram(6, 10);
histogram(11, 15);
etc.

Basically, I would call it for every set of five numbers. It worked but it was super inefficient and not very reusable. The problem is that when I run this code (entering numbers 1- 10), I get this:

1 - 5: **********
6 - 10: *****
11 - 15: 
16 - 20: 
etc.

The first set of five outputs an asterix for every number in the array.

Sorry for the incredibly long post. Any help is much appreciated and thank you in advance.

The bug is that you are using i in this if-statement.

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

Switch it to arr and you should be good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM