java初学者,下面程序为什么运行结果有问题,一个类访问不到另一个类的变量??

publicclassCalculation{publicdoubleweight;publicdoubleheight;publicdoubleBMI;publicSt... public class Calculation {
public double weight;
public double height;
public double BMI;
public String state;

public void calculate(double weight, double height){
this.weight=weight;
this.height=height;
BMI=(weight*1.0*10000/(height)/(height));
BMI=(int)(BMI*10+0.5)/10.0;// round the number
if (BMI<18.5){
state="Underweight";
}
if(BMI>=18.5&&BMI<=24.9){
state="Normal";
}
if (BMI>=25&&BMI<=29.9){
state="Overweight";
}
if(BMI>=29.9){
state="Obese";
}
}
public double getWeight(){
return weight;
}
}

public class Display {

private Calculation cal= new Calculation();
public void display(){
System.out.println("Your weight: "+cal.getWeight()+"kg");
System.out.println("Your height: "+new Calculation().height+"cm");
System.out.println("Your BMI: "+new Calculation().BMI+"kg");
System.out.println("Your are in the "+new Calculation().state+" range");
}
}

public class BMI_tests {

public static void main(String[] args) {
double para1=Double.parseDouble(args[0]);
System.out.println(para1);
double para2=Double.parseDouble(args[1]);
System.out.println(para2);

Calculation ob=new Calculation();
Display ob2=new Display();
ob.calculate(para1,para2);
ob2.display();
}
}
输入72kg和170cm时,结果为:
Your weight: 0.0kg
Your height: 0.0cm
Your BMI: 0.0kg
Your are in the null range。
为什么Display类中,weight等变量没有得到Calculation中这些变量的数值?
展开
 我来答
suzhou2600
2011-09-17 · TA获得超过5730个赞
知道大有可为答主
回答量:3447
采纳率:62%
帮助的人:1360万
展开全部
Display类中定义了一个自己的对象,如下
private Calculation cal= new Calculation();
还有后面三句打印语句的new Calculation(),都是重新定义了变量。
运行是打印的是这些对象变量的值,在Display类中没有给他们赋值,所以打印时,是没有结果的。

修改如下:
public class Display {

private Calculation cal ;
public void display(Calculation calPara ){
cal = calPara ;
System.out.println("Your weight: "+cal.getWeight()+"kg");
System.out.println("Your height: "+cal..height+"cm");
System.out.println("Your BMI: "+cal.BMI+"kg");
System.out.println("Your are in the "+cal..state+" range");
}
}

public class BMI_tests {

public static void main(String[] args) {
double para1=Double.parseDouble(args[0]);
System.out.println(para1);
double para2=Double.parseDouble(args[1]);
System.out.println(para2);

Calculation ob=new Calculation();
Display ob2=new Display();
ob.calculate(para1,para2);
ob2.display(ob);
}
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式