应该这样写:
class Box{
double width ;
double heigth ;
double depth ;
void volume(){
System.out.print("volume is ") ;
System.out.println(width * heigth * depth) ;
}
void setDim(double wid,double hei,double depth){
width = wid;
heigth = hei ;
depth = depth ;
}
}class BoxDemo{
public static void main(String[] lianga){
Box mybox = new Box() ;
mybox.width = 10;
mybox.heigth = 20;
mybox.depth = 30;
// mybox.setDim(10,20,30) ;
mybox.volume();
}
}
class Box{
double width ;
double heigth ;
double depth ;
void volume(){
System.out.print("volume is ") ;
System.out.println(width * heigth * depth) ;
}
void setDim(double wid,double hei,double depth){
width = wid;
heigth = hei ;
depth = depth ;
}
}class BoxDemo{
public static void main(String[] lianga){
Box mybox = new Box() ;
mybox.width = 10;
mybox.heigth = 20;
mybox.depth = 30;
// mybox.setDim(10,20,30) ;
mybox.volume();
}
}
一个很简单的问题,却很难搞明白到底是为什么。
double widt;
double heigt;
double dept;
public Box(){}
void volume(){
System.out.print("volume is ");
double volume = width * heigth * depth;
System.out.println(volume) ;
}
void setDim(double wid,double hei,double depth){
widt = wid;
heigt = hei ;
dept = depth ;
}
}
volume()中,没有使用这三个赋了值的变量,而是使用了在类Box中的变量,因为这几个没有赋值,所以运算出的结果不是理想中的结果
width = wid;
heigth = hei ;
depth = depth ;
你的上面的double depth的depth换个名字就可以了!因为一般默认情况下初始化数据为0
this.depth = depth;就可以了。