作业帮 > 综合 > 作业

java有一题执行结果不对,但是我不知道错在哪里了,求高手认真解释,谢谢!执行结果始终为0.

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/18 09:07:12
java有一题执行结果不对,但是我不知道错在哪里了,求高手认真解释,谢谢!执行结果始终为0.
题目:
定义一个名为Cuboid的长方体类,使其继承Rectangle类,其中包含一个表示高度的double型成员变量height,定义一个构造方法Cuboid(double length,double width,double height)和一个求长方体体积的volume()方法.编写一个应用程序,在其中求一个长、宽和高分别为10、5、2的长方体的体积.
源程序:
class Rectangle{
double length;
double width;
public Rectangle(){
}
public Rectangle(double length,double width){
this.length=length;
this.width=width;
}
public void setWidth(double width){
this.width=width;
}
public void setLength(double Length){
this.length=length;
}
public double area(){
return length*width;
}
}
class Cuboid extends Rectangle{
double height;
public Cuboid(){
this(0,0,0);
}
public Cuboid(double length,double width,double height){
super(length,width);
this.height=height;
}
public void setHeight(double height){
this.height=height;
}
public void setWidth(double width){
this.width=width;
}
public double volume(){
return area()*height;
}
}
class CuboidTest{
public static void main(String[] args){
Cuboid cb=new Cuboid();
cb.setLength(10);
cb.setWidth(5);
cb.setHeight(2);
System.out.println("volume="+cb.volume());
}
}
-----------------------------存在问题的代码-------------------------
类Rectangle中
public void setLength(double Length){
this.length=length;
}
-----------------------java对字母大小写敏感----------------------
错误:setLength() 方法的参数是double Length,但是初始化的时候是this.length =length
大小写问题啊Length:length.
你这样的错误导致length没有被成功赋值,length始终是类初始化给的默认值0,所以求体积肯定一直为0了.
解决方法:修改方法参数double Length修改成 double length