将我的Java代码分成两个方法

时间:2016-11-24 17:40:44

标签: java

我希望我的main方法包含一个人的体重和身高的输入值,然后让它调用bodyMassIndex方法来获得健康观点(即正常体重),然后输出。想知道是否有人可以帮助我?

package bodymassindex;
import java.util.Scanner;

 public class BodyMassIndex {
 public static void main(String[] args) {

  double m; 
  double kg;   
  double bmi;

Scanner input = new Scanner(System.in);

 System.out.println("Enter weight (KG): ");
 kg = input.nextDouble();

 System.out.println("Enter height (M): ");
 m = input.nextDouble();

 bmi = kg / (m*m);

 System.out.println("Your BMI is " + bmi);

 if (bmi < 16)
   System.out.println("Seriously underweight");
 else if (bmi >= 16 && bmi < 18)
   System.out.println("Underweight");
 else if (bmi >= 18 && bmi < 24)
   System.out.println("Normal weight");
 else if (bmi >= 24 && bmi < 29)
   System.out.println("Overweight");
 else if (bmi >= 29 && bmi < 35)
   System.out.println("Seriously overweight");
 else if (bmi >= 35 )
   System.out.println("Obese");
 }
}

1 个答案:

答案 0 :(得分:0)

将其分解为自己的方法,并创建一个传入一些测试参数的方法。还包括用于输入用户输入的功能。

package bodymassindex;
import java.util.Scanner;

public class BodyMassIndex {
    public static void main(String[] args) {
        double m; 
        double kg;
        Scanner input = new Scanner(System.in);

        System.out.println("Enter weight (KG): ");
        kg = input.nextDouble();

        System.out.println("Enter height (M): ");
        m = input.nextDouble();

        bmi(kg, m);
        // bmiTest(); /* Uncomment to run some "test" values.*/
   }

   private static void bmiTest() {
       bmi(100, 2);
       bmi(50, 1.3);
       bmi(60, 1.8);
   }

   private static void bmi(double kg, double m) {
        double bmi = kg / (m*m);
        System.out.println("Your BMI is " + bmi);

        if (bmi < 16)
          System.out.println("Seriously underweight");
        else if (bmi >= 16 && bmi < 18)
          System.out.println("Underweight");
        else if (bmi >= 18 && bmi < 24)
          System.out.println("Normal weight");
        else if (bmi >= 24 && bmi < 29)
          System.out.println("Overweight");
        else if (bmi >= 29 && bmi < 35)
          System.out.println("Seriously overweight");
        else if (bmi >= 35 )
          System.out.println("Obese");
   }
}