JAVA: BMI Calculator using

2019-09-22 06:13发布

问题:

I am very new to java trying to build a simple BMI calculator using a constructor, a public instance method and a toString method.

public class BMI {

public BMI(String name, double height, double weight){

}

public String getBMI() {
    return (weight/height);
  }


  public String toString() {
        return name + "is" + height + "tall and is " + weight +
                "and has a BMI of" + getBMI() ;
      }

public static void main(String[] args) {


}

i don't really know what i'm doing, so all help is appreciated. If you know how to complete this and can show me a main method which can demonstrate how to use it that would be even more appreciated.

thanks :)

回答1:

Since you're a beginner I'm posting full code to get you going.

public class BMI {
String name;
double height;
double weight;
public BMI(String name, double height, double weight){
   this.name=name;
   this.height=height;
   this.weight=weight;
}

public String getBMI() {
    return (weight/height);
  }


  public String toString() {
        return name + "is" + height + "tall and is " + weight +
                "and has a BMI of" + getBMI() ;
      }

public static void main(String[] args) {
     System.out.println(new BMI("Sample",2,4));

}

Output

Sample is 2 tall and is 4 and has a BMI of 2



回答2:

You have only local variables in constructor.

public class BMI {

String name;
double height, weight;

public BMI(String name, double height, double weight){
    this.name = name;
    this.height = height;
    this.weight = weight;
}

public double getBMI() {
    return (weight/height);
  }


  public String toString() {
        return name + "is" + height + "tall and is " + weight +
                "and has a BMI of" + getBMI() ;
      }

public static void main(String[] args) {
     BMI obj = new BMI("John",77,44);
     System.out.println(obj);
     //or
     double bmi = obj.getBMI();
     System.out.println("BMI = "+bmi);


}


回答3:

You already have a code so I'll just mention that BMI is weight (in kg) divided by height (in m) squared