Java中的BMI计算

时间:2015-06-27 18:36:34

标签: java ioexception

我是Java新手。今天,我正在做关于BMI计算的java项目。

到目前为止我的代码是:

package extra_programs;
import java.io.*;


public class bmiCalculation {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
          BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
          System.out.println("Enter your weight in kgs");
          int  wt=Integer.parseInt( reader.readLine());
          System.out.println("Enter your weight in cms");
          double height=Double.parseDouble(reader.readLine());
          height=height/100;
          double bmi=wt/(height*height);

          if(bmi<18.5){
              System.out.println("You are underweight");
          }
          else if(bmi>=18.5 && bmi<25){
              System.out.println("You are The right weight");
          }
          else if(bmi>=25 && bmi<30){
              System.out.println("You are overweight,Plz start jogging");
          }
          else if(bmi>=30){
              System.out.println("You are obese,Plz start jogging and tryt to reduce weight.");
          }
          else{
              System.out.println("Not a valid bmi");
          }



    }

}

每当我编写程序时,错误都会弹出:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    Unhandled exception type IOException
    Unhandled exception type IOException

    at extra_programs.bmiCalculation.main(bmiCalculation.java:13)

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:2)

通过添加投掷声明来修改您的主要

 public static void main(String[] args) throws  IOException {

因为reader.readLine()可能会抛出未处理的异常。

答案 1 :(得分:1)

您应该使用 try / catch 块来包围您的代码,该块将捕获潜在的 IOExceptions

像这样:

public class bmiCalculation {

    public static void main(String[] args) {
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter your weight in kgs");
      try {
           int wt=Integer.parseInt(reader.readLine());
           System.out.println("Enter your weight in cms");
           double height=Double.parseDouble(reader.readLine());
           height=height/100;
           double bmi=wt/(height*height);
           if(bmi<18.5) {
             System.out.println("You are underweight");
           }
           else if(bmi>=18.5 && bmi<25) {
             System.out.println("You are The right weight");
           }
           else if(bmi>=25 && bmi<30) {
             System.out.println("You are overweight,Plz start jogging");
           }
           else if(bmi>=30) {
             System.out.println("You are obese,Plz start jogging and try to reduce weight.");
           }
           else {
             System.out.println("Not a valid bmi");
           }
      }
      catch(IOException e) {
             System.out.println("Exception caught: " + e.printStackTrace());
      }
   }           
}