我的BMI计算器出了什么问题?

时间:2015-06-18 23:44:14

标签: java class methods calculator

我正在尝试制作一个BMI计算器,它调用一个单独的类的方法来计算bmi,然后继续在main方法中。以下是我的源代码。

import java.util.Scanner;

public class testBMI
{
    public static void main(String[] args)
    {
        String name;
        double bmi;
        String bmiClass;
        char z;

        Scanner readinput = new Scanner(System.in);

        do
        {   
        System.out.print("Please enter your name: ");
        name = readinput.nextLine();

        BMI.calculateBMI();

        if (bmi < 18.5)
        {
            bmiClass = "(Underweight)";
        }
        else
            if (bmi >= 18.5 && bmi <= 25)
            {
                bmiClass = "(Normal)";
            }
            else
                if (bmi > 25.0 && bmi <= 30.0)
                {
                    bmiClass = "(Overweight)";
                }
                else
                    bmiClass = "(Obese)";

        System.out.println(name + ", your BMI is " +bmi+ "" +bmiClass+ ".");    
        System.out.print("Type Y or y to continue, or any other key to quit: ");
        z = readinput.next().charAt(0);
        } while (z == 'Y' || z == 'y');
    }
}

另一堂课:

import java.util.Scanner;

public class BMI
{

    public static void calculateBMI()
    {

        Scanner readinput = new Scanner(System.in);

        double weight;
        double height;
        double newWeight;
        double newHeight;
        double bmi;

        System.out.print("Please enter your weight in pounds: ");
        weight = readinput.nextInt();

        System.out.print("Please enter your height in inches: ");
        height = readinput.nextInt();

        newWeight = weight * 0.45359237;

        newHeight = height * 0.0254;

        bmi = newWeight/(newHeight*newHeight);

    }
}

编译这些文件时,我成功编译了我的方法类(第二个片段),但在第一个文件中得到1个错误,其内容如下:

testBMI.java:21: error: variable bmi might not have been initialized
        if (bmi < 18.5)
            ^
1 error

变量bmi显然是声明的,但初始化(添加到变量的实际值)发生在单独的方法中,但是,我不知道为什么main方法没有从第二个运行中识别它的初始化方法。请告诉我我做错了什么。

3 个答案:

答案 0 :(得分:1)

您需要在BMI类中返回bmi的值。当你在testBMI类中检查bmi的值时,它只在你的BMI类中进行了本地初始化,而不是你的testBMI类。

答案 1 :(得分:0)

进行以下更改
1。来自public static void calculateBMI()
public static double calculateBMI()


2。来自bmi = newWeight/(newHeight*newHeight);
return newWeight/(newHeight*newHeight);


3.来自BMI.calculateBMI();
bmi = BMI.calculateBMI();

答案 2 :(得分:0)

您的public static void calculateBMI()方法应为public static double calculateBMI()并返回bmi变量。

接下来在main方法中,在调用BMI.calculateBMI()时,您应该将返回值分配给bmi变量。

其余代码看起来不错。

您遇到的问题是变量的范围main方法不知道来自bmi类的BMI变量,因为此变量(甚至与main类中的变量命名相同)是本地的。

此外,您收到警告,因为已声明 bmi变量,但已初始化。当您尝试检查语句if (bmi < 18.5)时,您的程序&#34;不知道&#34; bmi的价值是什么。

相关问题