首页 > 解决方案 > 如何在 Java 中验证用户输入

问题描述

我写了一个 bmi 计算器程序,我想验证用户输入,这样用户就不会为身高或体重输入输入负数。

我该怎么做呢?我是Java新手,所以我不知道。

import java.util.Scanner;
 
public class BMICalculator {
 
    public static void main(String[] args) throws Exception {
        calculateBMI();
    }
 
    private static void calculateBMI() throws Exception {
        System.out.print("Please enter your weight in kg: ");
        Scanner s = new Scanner(System.in);
        float weight = s.nextFloat();
        System.out.print("Please enter your height in cm: ");
        float height = s.nextFloat();
         
        float bmi = (100*100*weight)/(height*height);
         
        System.out.println("Your BMI is: "+bmi);
        printBMICategory(bmi);

        s.close();
       
    }
     

    private static void printBMICategory(float bmi) {
        if(bmi < 24) {
            System.out.println("You are underweight");
        }else if (bmi < 29) {
            System.out.println("You are healthy");
        }else if (bmi < 34) {
            System.out.println("You are overweight");
        }else {
            System.out.println("You are OBESE");
        }
    }
}

标签: javavalidationcalculator

解决方案


您可以继续要求价值,直到用户输入有效数字

private float readZeroOrPositiveFloat(Scanner scanner , String promptMessage) 
{
     float value = -1;
     while(value < 0){
         System.out.println(promptMessage);
         value = scanner.nextFloat();
     }
     return value;
}


private static void calculateBMI() throws Exception {
    System.out.print("Please enter your weight in kg: ");
    Scanner s = new Scanner(System.in);
    float weight = readZeroOrPositiveFloat(s , "Please enter your weight in kg: ");
    float height = readZeroOrPositiveFloat(s , "Please enter your height in cm: ");
     
    float bmi = (100*100*weight)/(height*height);
     
    System.out.println("Your BMI is: "+bmi);
    printBMICategory(bmi);

    s.close();
   
}

推荐阅读