You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何为Java统计程序添加1-50数值区间的直方图功能?

Fixing the Histogram & Mode Functionality for Your Java Program

Hey there! Let's get your histogram working properly, and while we're at it, fix the mode method too (it wasn't actually finding the most frequent number yet). Here's a breakdown of what was off with your current code and a fully working solution:

Issues in Your Original Code

First, let's go over the problems in your existing graph method:

  • You were modifying the original array with arr[i]++, which corrupts your input data for other calculations
  • The logic for checking intervals was mixed in a single loop, meaning you weren't grouping counts by each range correctly
  • Only two intervals were being handled, not all ranges from 1-5 up to 46-50
  • Your mode method just returned the first element of the array, not the most frequent value

Fully Corrected Code

Here's the complete, working program with all features (including the histogram) fixed:

import java.util.Scanner;

public class NumberStats {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Enter the amount of numbers you would like to enter: ");
        int amount = scan.nextInt();
        int[] arr = new int[amount];
        
        for (int i = 0; i < arr.length; i++) {
            System.out.println("Enter a number 1 through 50");
            int outcome = scan.nextInt();
            // Validate input to ensure it's within 1-50
            while (outcome < 1 || outcome > 50) {
                System.out.println("Invalid number! Please enter a number between 1 and 50:");
                outcome = scan.nextInt();
            }
            arr[i] = outcome;
        }

        System.out.println("\nThe average is:");
        System.out.println(average(arr));
        System.out.println("\nThe lowest value in the array is:");
        System.out.println(min(arr));
        System.out.println("\nThe largest value in the array is:");
        System.out.println(max(arr));
        System.out.println("\nThe most frequent number in the array is:");
        System.out.println(mode(arr));
        System.out.println("\nHistogram:");
        graph(arr);
        
        scan.close();
    }

    public static double average(int[] arr) {
        double sum = 0;
        for (int num : arr) {
            sum += num;
        }
        return sum / arr.length;
    }

    public static int max(int[] arr) {
        int max = arr[0];
        for (int num : arr) {
            if (num > max) {
                max = num;
            }
        }
        return max;
    }

    public static int min(int[] arr) {
        int min = arr[0];
        for (int num : arr) {
            if (num < min) {
                min = num;
            }
        }
        return min;
    }

    public static int mode(int[] arr) {
        int mode = arr[0];
        int maxCount = 0;
        
        for (int num : arr) {
            int count = 0;
            for (int compareNum : arr) {
                if (compareNum == num) {
                    count++;
                }
            }
            if (count > maxCount) {
                maxCount = count;
                mode = num;
            }
        }
        return mode;
    }

    public static void graph(int[] arr) {
        // Define interval parameters: start at 1, each interval is 5 numbers
        int intervalSize = 5;
        int start = 1;
        
        // Loop through all intervals from 1-5 up to 46-50
        while (start <= 50) {
            int end = start + intervalSize - 1;
            // Cap end at 50 to avoid going over
            end = Math.min(end, 50);
            
            // Count how many numbers fall into this interval
            int count = 0;
            for (int num : arr) {
                if (num >= start && num <= end) {
                    count++;
                }
            }
            
            // Print the interval label and corresponding asterisks
            System.out.printf("%d - %d: ", start, end);
            for (int i = 0; i < count; i++) {
                System.out.print("*");
            }
            // Add space between intervals for readability
            System.out.print(" ");
            
            // Move to next interval
            start += intervalSize;
        }
    }
}

Key Improvements Explained

  1. Input Validation: Added a loop to ensure users only enter numbers between 1 and 50, so your data stays consistent
  2. Fixed Mode Method: Now it actually counts occurrences of each number and returns the one with the highest frequency
  3. Proper Histogram Logic:
    • Uses a loop to generate each interval dynamically (no hardcoding all 10 intervals manually)
    • Counts numbers per interval without modifying the original array
    • Prints each interval's label followed by the correct number of * characters, matching the format you wanted
  4. Cleaner Code: Used enhanced for-loops (for (int num : arr)) where possible to make the code more readable

Example Output

If you input numbers that match your sample expected output, the histogram will look exactly like this:

1 - 5: **** 6 - 10: ****** 11 - 15: ** 16 - 20: ********** 21 - 25: *********** 26 - 30: ******** 31 - 35: **** 36 - 40: ******* 41 - 45: ************ 46 - 50: ***************** 

内容的提问来源于stack exchange,提问作者calvin jackson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:42:25