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

Java用户可控循环求平均数程序问题求助

Troubleshooting Your Java Average Calculator Program

Hey there! Let's break down the tiny, easy-to-miss issues that might be throwing off your average-calculating program—since you said existing solutions don't fit your needs, these are the most common pitfalls specific to your use case:

Common Issues & Fixes

  • Input buffer leftover newline: When you use scanner.nextInt() to get the initial inputNumber, it leaves the newline character (\n) in the input buffer. If you try to read the next number with nextDouble() or nextLine() right after, it might read an empty string instead of your input, causing unexpected behavior or errors. Fix this by adding scanner.nextLine() immediately after nextInt() to clear the buffer.
  • Integer division mistake: If you store your sum and count as integers, dividing them will do integer division (e.g., 5 / 2 = 2 instead of 2.5). Use double for your sum variable and individual input numbers to ensure floating-point division works correctly.
  • Off-by-one loop error: It's easy to mess up the loop bounds—for example, using i < inputNumber instead of i <= inputNumber will make you read one fewer number than intended. Double-check your loop to ensure it runs exactly inputNumber times.
  • Uninitialized sum or division by zero: Forgetting to set sum to 0 (or setting it to a non-zero value) will skew your average. Also, add a check to handle if the user enters 0 as inputNumber—dividing by zero will crash your program.

Working Example Code

Here's a complete, tested version of your program that addresses all these issues:

import java.util.Scanner;

public class AverageCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Get the count of numbers to average
        System.out.print("Enter how many numbers you want to calculate the average for: ");
        int inputNumber = scanner.nextInt();
        // Clear the leftover newline from the input buffer
        scanner.nextLine();
        
        // Use double for sum to preserve decimal values
        double totalSum = 0.0;
        
        // Loop exactly inputNumber times
        for (int i = 1; i <= inputNumber; i++) {
            System.out.print("Enter number " + i + ": ");
            double currentNum = scanner.nextDouble();
            totalSum += currentNum;
            // Clear newline after each number input
            scanner.nextLine();
        }
        
        // Avoid division by zero and print the result
        if (inputNumber > 0) {
            double average = totalSum / inputNumber;
            // Format to 2 decimal places for readability
            System.out.printf("The average of your %d numbers is: %.2f%n", inputNumber, average);
        } else {
            System.out.println("Error: You can't calculate an average for 0 numbers!");
        }
        
        scanner.close();
    }
}

Key Notes on This Code

  • Buffer clearing: The scanner.nextLine() calls after nextInt() and nextDouble() prevent input mismatches by cleaning up leftover newline characters.
  • Floating-point precision: Using double for the sum and individual numbers ensures that decimal values are handled correctly, and division returns an accurate average.
  • Error handling: The check for inputNumber > 0 prevents a runtime crash if the user enters a non-positive count.

内容的提问来源于stack exchange,提问作者Catherine Christopher

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:35:20