【问题标题】:How to Calculate BMI in Java如何在 Java 中计算 BMI
【发布时间】:2016-11-24 04:47:01
【问题描述】:

我正在编写一个程序,它接受用户输入的身高和体重,然后据此计算体重指数。它对身高、体重和 BMI 使用单独的方法,这些方法是从 main 调用的。我遇到的问题是我完全不知道如何将体重和身高方法的输入放入 BMI 方法中。这就是代码的样子:

public class BMIProj {
    static Scanner input = new Scanner(System.in);
    public static int heightInInches()
    {

       System.out.println("Input feet: ");
       int x;
       x = input.nextInt();
       System.out.println("Input Inches: ");
       int y;
       y = input.nextInt();

       int height = x * 12 + y;

       return height; 
    }

    public static int weightInPounds()
    {
        System.out.println("Input stone: ");
        int x;
        x = input.nextInt();
        System.out.println("Input pounds ");
        int y;
        y = input.nextInt();

        int weight = x * 14 + y;

        return weight;
    }

    public static void outputBMI()
    {

    }

    public static void main(String[] args) {

        heightInInches();
        weightInPounds();
        outputBMI();

    }

提前致谢。

【问题讨论】:

  • 提示:“返回”很重要。下一个提示:您用“参数”标记了您的帖子,但您的任何函数都没有使用任何参数。
  • AFAIK,原始的 BMI 计算使用公制系统(身高单位为厘米,体重单位为公斤)。我猜你需要一个英制的换算系数。

标签: java methods parameters parameter-passing static-methods


【解决方案1】:

我建议你多学习一点java,特别是变量,声明,初始化等。还要学习类,构造函数等。

  1. 您需要类的字段来保存输入的变量
  2. 我创建了一个构造函数来初始化变量
  3. 如果您所做的只是为类字段分配值并输出信息,则无需在方法中返回任何内容。

我为你计算了 bmi 的屈膝礼

不管怎样

public class BMIProj {
    static Scanner input = new Scanner(System.in);

    // Class vars
   int height;
   int weight;
   double bmi;

   //Constructor
   public BMIPrj(){
     //Initialize vars 
     height = 0;
     weight = 0;
     bmi = 0;
   }

    public static void heightInInches()
    {

       System.out.println("Input feet: ");
       int x;
       x = input.nextInt();
       System.out.println("Input Inches: ");
       int y;
       y = input.nextInt();

       int height = x * 12 + y;

       return height; 
    }

    public static void weightInPounds()
    {
        System.out.println("Input stone: ");
        int x;
        x = input.nextInt();
        System.out.println("Input pounds ");
        int y;
        y = input.nextInt();

        int weight = x * 14 + y;

        return weight;
    }

    public static void outputBMI()
    {
      System.out.println("BMI: " + (( weight / height ) x 703));
    }

    public static void main(String[] args) {

        heightInInches();
        weightInPounds();
        outputBMI();

    }

【讨论】:

    【解决方案2】:

    您可以将方法的输出分配给参数,如下所示:

    int weight = weightInPounds();

    调用方法时,可以传入参数:

    outputBMI(weight);

    剩下的看你自己了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多