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

如何用循环与多方法实现五人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.

Step 1: Define Core Components (Multi-Method Split)

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
Step 2: Fix Input & Buffer Issues

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);
    }
Step 3: Implement BMI Calculation

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);
    }
Step 4: Add Result Output

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);
    }
Step 5: Tie It All Together in Main

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();
    }
}
Key Fixes & Tips to Avoid Issues
  • Buffer Handling: The scanner.nextLine() after nextDouble() fixes the common issue where the next nextLine() 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:44:56