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 initialinputNumber, it leaves the newline character (\n) in the input buffer. If you try to read the next number withnextDouble()ornextLine()right after, it might read an empty string instead of your input, causing unexpected behavior or errors. Fix this by addingscanner.nextLine()immediately afternextInt()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 = 2instead of2.5). Usedoublefor 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 < inputNumberinstead ofi <= inputNumberwill make you read one fewer number than intended. Double-check your loop to ensure it runs exactlyinputNumbertimes. - Uninitialized sum or division by zero: Forgetting to set
sumto0(or setting it to a non-zero value) will skew your average. Also, add a check to handle if the user enters0asinputNumber—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 afternextInt()andnextDouble()prevent input mismatches by cleaning up leftover newline characters. - Floating-point precision: Using
doublefor the sum and individual numbers ensures that decimal values are handled correctly, and division returns an accurate average. - Error handling: The check for
inputNumber > 0prevents a runtime crash if the user enters a non-positive count.
内容的提问来源于stack exchange,提问作者Catherine Christopher
相关产品推荐
相关产品推荐

