我一直在为我的
java类做一个项目.对于项目,我必须让用户输入输入并计算他们的体重指数和体表面积,程序应该保持运行直到用户输入“q”.当一个“q”被放入它时,我无法让我的程序停止运行.另外我对java和编程也很新,所以我将不胜感激.我的代码如下.
谢谢 : )
public static void main(String[] args) {
//Scanner
Scanner stdIn = new Scanner(System.in);
//Variables
final double METERS_TO_CM = 100; // The constant to convert meters to centimeters
final double BSA_CONSTANT = 3600; // The constant to divide by for bsa
double bmi; // Body Mass Index
String weight; // Weight in kilograms
String height; // Height in meters
String classification; // Classifies the user into BMI categories
double bsa; // Body surface area
do {
System.out.print("Welcome to the BMI and BSA Calculator to begin enter weight in kilograms.");
weight = stdIn.next();
System.out.print("Enter height in meters: ");
height = stdIn.next();
double height2 = Double.parseDouble(height);
double weight2 = Double.parseDouble(weight);
bmi = weight2/(height2*height2);
if (bmi < 18.5)
{
classification = "Underweight";
}
else if (bmi < 25)
{
classification = "Normal";
}
else if (bmi < 30)
{
classification = "Overweight";
}
else
{
classification = "Obese";
}
System.out.println("Your classification is: " + classification);
bsa = Math.sqrt(((height2*METERS_TO_CM)*weight2)/BSA_CONSTANT);
System.out.printf("BMI: %.1f\n", bmi);
System.out.printf("BSA: %.2f\n", bsa);
System.out.println("Hit 'q' to quit");
} while (stdIn.nextLine().compareToIgnoreCase("q")==0);
}
}
最佳答案 我猜你的“q”输入是用权重写的,因此你试图将它解析为Double,它抛出一个未处理的Exception并停止执行.
您应该处理此异常并在触发它时使系统中断while循环.