我写的是一个判断体型的程序,其中有一个方法drawResult()用来输出最后的结果,在方法drawResult()里使用了if else语句以判断当体重指数不同时的结论,但是if else语句会跳过之前的if 、else if语句,直接执行最后的语句,不考虑判断条件
package tixingpd;
abstract class people{
double weight;
double height;
people(int w,int h){
weight=w;
height=h;
}
abstract public double stature();
public class drawResult {
}
}
class man extends people{
man(int w,int h) {
super(w,h); }
public double stature()
{
double BMI;
height=height/100;
weight=weight/2;
BMI=weight/(height*height);
return BMI;
}
public void drawResult() {
// TODO 自动生成的方法存根
System.out.println("身高:" +height);
System.out.println("体重:" +weight);
System.out.println("体重指数:" +stature());
if(stature()<18)
System.out.println("较瘦");
else if(stature()<25)
System.out.println("正常");
else System.out.println("较胖");
}
}
class woman extends people{
woman(int w,int h) {
super(w,h); }
public double stature()
{
double BMI;
height=height/100;
weight=weight/2;
BMI=weight/(height*height);
return BMI;
}
public void drawResult()
{
System.out.println("身高:" +height);
System.out.println("体重:" +weight);
System.out.println("体重指数:" +stature());
if(stature()<18)
System.out.println("较瘦");
else if(stature()<25)
System.out.println("正常");
else System.out.println("较胖");
}
}
public class drawResult {
public static void main(String args[]) {
man no1man=new man(130,170); //创建男性对象
System.out.println(" this man :");
no1man.drawResult( );
//输出男性的体重,身高,体型结论
woman nolwoman=new woman(110,160); //创建女性对象
System.out.println(" this woman :");
nolwoman.drawResult( );
//输出女性的体重,身高,体型结论
}
}
我不知道是不是软件的问题,我使用的是eclipse。
多次执行stature方法,然后stature方法又多次使用成员变量/100和2,最终导致所有条件判断失败。
stature方法改成:
private int stature(){
return weight/(height*height/10000*2);
}
即可
另外方法如果结果一致尽量不要多次调用,用int值接收判断就行了
int result = stature();
if (result<18){
...
}...
构造函数int换成double
abstract public double stature();
/*
public class drawResult {
}去掉*/
public double stature()
{
double BMI;
BMI=weight/2*10000/(height*height);
return BMI;
}
public void drawResult()
{
System.out.println("身高:" +height);
System.out.println("体重:" +weight);
System.out.println("体重指数:" +stature());
double BMI = stature();
if(BMI<18)
System.out.println("较瘦");
else if(BMI<25)
System.out.println("正常");
else System.out.println("较胖");
}