我最近刚刚开始按照我的教授的要求使用记事本使用Java进行编码,并且需要创建一个BMI计算器(我以前在C ++中已经做过)。但是,尽管我的类和驱动程序都进行了编译-并且我没有看到任何错误-,但程序输出在应返回浮点数时返回了“ NaN”。谁能让我知道我哪里出了问题?该类的代码:
import java.util.Scanner;
public class BMICalculator
{
Scanner input = new Scanner(System.in);
float weight;
float height;
float bmi;
public float calculateBMI()
{
bmi = (weight / (height * height)) * 703;
}
public void setWeight(float aWeight)
{
weight = aWeight;
}
public void setHeight(float aHeight)
{
height = aHeight;
}
public float getWeight()
{
return weight;
}
public float getHeight()
{
return height;
}
public float getBMI()
{
return bmi;
}
public void ask()
{
System.out.print("Enter a weight in pounds: ");
weight = input.nextFloat();
System.out.print("Enter a height in inches: ");
height = input.nextFloat();
calculateBMI();
}
public void show()
{
System.out.println();
System.out.println("Body Mass Index: " + bmi);
if (bmi <= 0)
{
System.out.println("Something went wrong...");
}
else if (bmi >= 1.0 && bmi < 18.5)
{
System.out.println("Underweight.");
}
else if (bmi >= 18.5 && bmi < 25.0)
{
System.out.println("Normal weight.");
}
else if (bmi >= 25.0 && bmi < 30.0)
{
System.out.println("Overweight.");
}
else if (bmi >= 30.0)
{
System.out.println("Obese.");
}
}
}
驱动程序主代码:
public class BMICalculatorDriver
{
public static void main(String [] args)
{
BMICalculator userBMI = new BMICalculator();
userBMI.ask();
userBMI.show();
}
}