[英]Java how to use toString method to return an accessor method
我已经为此工作了一段时间,似乎无法理解它。 我正在尝试使用访问器方法从长度、高度和宽度(不将体积或表面积放在数据字段中)计算体积和表面积。 我不确定为什么我的代码会出现这些错误(见下文),并且会感谢一些教育,因为我真的在努力学习如何编码:谢谢 :)
错误:找不到符号符号:可变音量位置:class Box
错误:找不到符号符号:可变表面区域位置:class 框
public class Box {
//data field declarations
public int height; //height
public int width; //width
public int length; //length
/**sets the value of the data field height to input parameter value*/
public void setheight(int H){
height = H;
}
//end method
/**sets the value of the data field width to input parameter value*/
public void setwidth(int W){
width = W;
}
//end method
/**sets the value of the data field length to input parameter value*/
public void setlength(int L){
length = L;
}
//end method
/**A constructor which takes 3 parameters**/
public Box(int H, int L, int W){
H = height;
L = length;
W = width;
}
/**Constructor which creates a box**/
public Box(){
}
/**Constructor which creates a cube**/
public Box(int side){
side = height;
side = length;
side = width;
}
/**returns the value of the data field SurfaceArea **/
int getsurfaceArea(){
return (2*height) + (2*width) + (2*length);
}
//end method
/**returns the value of the data field volume */
int getvolume(){
return height*width*length;;
}
//end method
/**displays formatted Box information to the console window */
public String toString(){
return "Height is: " + height + ", Length is: " + length + ", Width is: " + width + ", Volume is: " + volume + ", Surface Area: " + surfaceArea;
}
//end method
}
您的方法中有一些编译错误:
return "Height is: " + height + ", Length is: " + length + ", Width is: " + width + ", Volume is: " + getvolume() + ", Surface Area: " + getsurfaceArea();
您将方法称为属性。
在您的构造函数中,您以错误的方式将方法变量分配给 class 属性。
所以你有这个:
/**
* A constructor which takes 3 parameters
**/
public Box(int H, int L, int W) {
H = height;
L = length;
W = width;
}
你真正想要的是:
/**
* A constructor which takes 3 parameters
**/
public Box(int H, int L, int W) {
this.height = H;
this.length = L;
this.width = W;
}
=
左边应该是 class 成员,右边是参数值。
使用this
关键字来跟踪哪个是哪个可能是个好主意。
最后在toString
方法中,需要调用方法计算体积和表面积
return "Height is: " + height + ", Length is: " + length + ", Width is: " + width + ", Volume is: " + getvolume() + ", Surface Area: " + getsurfaceArea()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.