如何用循环与多方法实现五人BMI计算(Scanner输入,解决输出问题)
Hey there! Let's get your BMI calculator back on track and finish it up properly. Since you're using a multi-method approach, we'll break this into clear, manageable steps to fix the output issue and complete the program.
First, let's formalize the methods to separate concerns—this makes your code cleaner and easier to debug:
- A method to collect user input (name, weight, height)
- A method to calculate BMI using the standard formula
- A method to print formatted results (including BMI category)
- A main method to handle the 5-person loop
A common reason for missing output or broken input is unhandled newline characters in the Scanner buffer. Let's build a robust input method first. We'll also use a simple Person class to bundle user data (instead of passing multiple variables around):
// Helper class to store user info class Person { private String name; private double weight; // in kg private double height; // in meters (convert cm to m if needed) public Person(String name, double weight, double height) { this.name = name; this.weight = weight; this.height = height; } // Getters to access private fields public String getName() { return name; } public double getWeight() { return weight; } public double getHeight() { return height; } }
Then the input method:
import java.util.Scanner; public class BMICalculator { private static Person getPersonInfo(Scanner scanner) { System.out.print("Enter name: "); String name = scanner.nextLine(); System.out.print("Enter weight (kg): "); double weight = scanner.nextDouble(); System.out.print("Enter height (m): "); double height = scanner.nextDouble(); // Critical: Consume the leftover newline to avoid skipping next name input scanner.nextLine(); return new Person(name, weight, height); }
This method is straightforward, but add a check for invalid values (no zero/negative weight/height):
private static double calculateBMI(double weight, double height) { if (weight <= 0 || height <= 0) { throw new IllegalArgumentException("Weight and height must be positive numbers!"); } // BMI formula: weight (kg) / (height (m) * height (m)) return weight / (height * height); }
This is where you'll fix the "no output" problem—make sure you call this method after calculating BMI! We'll also add category labels for better readability:
private static void printBMIResult(String name, double bmi) { String category; if (bmi < 18.5) { category = "Underweight"; } else if (bmi < 24.0) { category = "Normal weight"; } else if (bmi < 28.0) { category = "Overweight"; } else { category = "Obese"; } // Format output to 2 decimal places for clarity System.out.printf("%s's BMI: %.2f | Category: %s%n", name, bmi, category); }
Finally, set up the loop for 5 people and connect all methods:
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); for (int i = 0; i < 5; i++) { System.out.println("\n--- Person " + (i + 1) + " ---"); try { Person person = getPersonInfo(scanner); double bmi = calculateBMI(person.getWeight(), person.getHeight()); printBMIResult(person.getName(), bmi); } catch (IllegalArgumentException e) { // Handle invalid input gracefully System.out.println("Error: " + e.getMessage()); scanner.nextLine(); // Reset buffer after invalid input } } scanner.close(); } }
- Buffer Handling: The
scanner.nextLine()afternextDouble()fixes the common issue where the nextnextLine()reads an empty string instead of the name. - Unit Consistency: If your users input height in centimeters instead of meters, modify the input method to divide by 100:
height = scanner.nextDouble() / 100; - Error Handling: The try-catch block prevents the program from crashing if someone enters non-numeric values or invalid weights/heights.
- Verify Method Calls: Double-check that you're actually calling
printBMIResult()after calculating BMI—this is the most likely reason you're seeing no output right now!
内容的提问来源于stack exchange,提问作者Gray

