Java 11.6 我是Java的新手,并试图创建一个BMI计算器,该计算器将计算人的体重,身高并计算BMI。该程序接收数据,但不显示BMI计算的任何答案。由于没有错误,我不确定我的算法是错误的还是基本的编码错误。
人体重.java类
import java.time.Year;
public class PersonWeight {
private double height;
private double weight;
public PersonWeight() {
height = 0;
weight = 0;
}
public PersonWeight(double h, double w) {
height = h;
weight = w;
}
public void setHeight(double h) {
this.height = h;
}
public double getHeight() {
return height;
}
public void setWeight(double w) {
this.weight = w;
}
public double getWeight() {
return weight;
}
public double ComputeBMI() {
double bmi = ((weight)/(height*height));
return bmi;
}
}
具有 main 方法的测试类
import java.util.Scanner;
public class TestPersonWeight {
public static void classifyBMI() {
PersonWeight test1 = new PersonWeight();
String result="";
if(test1.ComputeBMI() < 18.5) {
result = "Underweight ";
} else if (test1.ComputeBMI() < 25) {
result = "Normal Weight ";
}else if (test1.ComputeBMI() < 30) {
result = "Over Weight ";
}else {
result = "Obese ";
}
System.out.printf(result);
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
TestPersonWeight TestPersonWeight = new TestPersonWeight();
PersonWeight PersonWeight = new PersonWeight()
System.out.printf("Enter person's Height in Meters: ");
double h = input.nextDouble();
PersonWeight.setHeight(h);
System.out.printf("Enter person's Weight in Kilograms: ");
double w = input.nextDouble();
PersonWeight.setWeight(w);
PersonWeight.ComputeBMI();
System.out.printf("%n Height: " + PersonWeight.getHeight());
System.out.printf("%n Weight: " + PersonWeight.getWeight());
System.out.printf("%n BMI: " , PersonWeight.ComputeBMI());
}
}
您的程序在最后一个System.out.printf()
命令中出错
System.out.printf("%n BMI: " + PersonWeight.ComputeBMI());
//Should be plus and not a comma (",")
在你的程序中,你用错了printf
。您有一些选择:
System.out.printf("%nHeight: %f", PersonWeight.getHeight());
System.out.printf("%nWeight: %f", PersonWeight.getWeight());
System.out.printf("%nBMI: %f", PersonWeight.ComputeBMI());
或者只使用System.out.println
:
System.out.println("Height: " + PersonWeight.getHeight());
System.out.println("Weight: " + PersonWeight.getWeight());
System.out.println("BMI: " + PersonWeight.ComputeBMI());
基本上,您的问题是您在最后一个语句中使用了逗号,因此没有打印它,但我也向您展示了其他选项。