java - 如何在 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");
}
}
}
解决方案
您可以继续要求价值,直到用户输入有效数字
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();
}
推荐阅读
- javascript - 离线优先 webapp 本地存储同步到 MySQL
- javascript - jquery 或 javascript 中有没有一种方法可以在不使用 ajax 请求的情况下在页面加载时填充下拉列表?
- javascript - 如何在通过 loadsh.js 绑定时在 html 输入标签中插入 JSON 字符串
- c++ - 无法将 const 数据类型传递给非 const 函数
- python-3.x - Python3 中的字节、字符串和 urllib
- javascript - onEdit 单元格 - 该脚本在编辑所有表格中的单元格 B4 时有效
- android - 如何为 Android 构建 LibVLC
- r - 如何修复警告“警告消息:在 nloptr(x0 = x0, eval_f = f,..... NAs 强制引入整数范围”
- java - 如何按多个属性在java8对象列表中排序
- javascript - 在函数/承诺范围之外使用对象