JAVA: BMI Calculator using

血红的双手。 提交于 2019-12-13 10:01:42

问题


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



来源:https://stackoverflow.com/questions/25644812/java-bmi-calculator-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!