【问题标题】:Java how to use toString method to return an accessor methodJava如何使用toString方法返回访问器方法
【发布时间】:2020-08-06 01:25:01
【问题描述】:

我已经为此工作了一段时间,但似乎无法理解它。我正在尝试使用访问器方法从长度、高度和宽度(不将体积或表面积放在数据字段中)计算体积和表面积。我不确定为什么我的代码会出现这些错误(见下文),并且会感谢一些教育,因为我真的在努力学习如何编码!谢谢你:)

错误:找不到符号 符号:可变体积 位置:类Box

错误:找不到符号 符号:可变表面积 位置:类Box

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

}

【问题讨论】:

  • 忽略get volume下的2个分号,删除:)
  • 在您的toString 方法中,您引用了一个名为volume 的变量,但此类中不存在此类变量。也许您的意思是getvolume()。同样,您的班级中不存在surfaceArea 变量,也许您的意思是getsurfaceArea()

标签: java methods tostring accessor


【解决方案1】:

您的方法中有一些编译错误:

   return "Height is: " + height + ", Length is: " + length + ", Width is: " + width + ", Volume is: " + getvolume() + ", Surface Area: " + getsurfaceArea();

您将方法称为属性。

【讨论】:

    【解决方案2】:

    在您的构造函数中,您以错误的方式将方法变量分配给类属性。

    所以你有这个:

        /**
         * 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;
        }
    
    

    = 的左侧应该是类成员,右侧应该是参数值。

    使用this 关键字来跟踪哪个是哪个可能是个好主意。

    最后在toString方法中,需要调用方法计算体积和表面积

    return "Height is: " + height + ", Length is: " + length + ", Width is: " + width + ", Volume is: " + getvolume() + ", Surface Area: " + getsurfaceArea()
    

    【讨论】:

      猜你喜欢
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 2023-03-22
      • 2021-10-21
      相关资源
      最近更新 更多