首先,我想说的是,在 Java 方面我是一个完整的初学者。到目前为止,我所知道的是我从大学的软件开发课程中学到的东西。我自己一直在搞砸它,我设法创建了一个应用程序,它以两个双精度值作为输入并计算用户的 BMI(体重指数)。
该程序运行良好,并且完全符合我的要求,但是,如果用户没有输入任何内容并按下回车键,则会引发异常。如果用户输入的不是数字,则会引发异常。当抛出异常时,程序停止。我想阻止这些异常完全停止程序,而是将用户返回到输入阶段并显示错误消息。
我知道它是如何完成的。有些人建议使用 try {..} catch (..) {..} 结构,我已经尝试过,但我总是设法破坏程序。
有人有想法么?
所以,这是我到目前为止的代码,如果有任何问题,我很抱歉,我已经尝试添加注释以使其更容易。
import java.io.*;
public class bmi {
public static void main(String[] args) throws IOException {
/**
* User input of weight and height.
*/
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter how much you weigh in KG.");
double weight = Double.parseDouble(in.readLine()); //take weight input as double
System.out.println("Please enter how tall you are in meters.");
double height = Double.parseDouble(in.readLine()); //take height input as double
/**
* BMI calculation
*/
double bmi = weight / Math.pow(height,2); // weight divided by height squared
/**
* if else statements to find if person is underweight, at a healthy weight or overweight.
*/
if (bmi<18.5) { //if BMI is smaller than 18.5
System.out.println("Your BMI is " + bmi + ", you are underweight.");
}
else if (bmi>=18.5 && bmi<=25) { //if BMI is bigger than or equal to 18.5 and smaller than or equal to 25
System.out.println("Your BMI is " + bmi + ", you are at a healthy weight.");
}
else if (bmi>25) { //if bmi is bigger than 25
System.out.println("Your BMI is " + bmi + ", you are overweight");
}
}
}
谢谢。