Java как использовать метод toString для возврата метода доступа - PullRequest
0 голосов
/ 06 августа 2020

Я работаю над этим какое-то время и, кажется, не могу осмыслить это. Я пытаюсь вычислить объем и площадь поверхности по длине, высоте и ширине (без указания объема или площади поверхности в полях данных) с помощью метода доступа. Я не уверен, почему в моем коде возникают эти ошибки (см. Ниже), и был бы признателен за некоторое обучение, поскольку я действительно пытаюсь научиться кодировать! Спасибо:)

Ошибка: не удается найти символ символа: местоположение переменного объема: класс 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

}

Ответы [ 2 ]

0 голосов
/ 06 августа 2020

В ваших конструкторах вы неправильно назначили переменную метода свойствам класса.

Итак, где у вас это:

    /**
     * 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()
0 голосов
/ 06 августа 2020

У вас есть ошибки компиляции в вашем методе:

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

Вы вызываете методы как атрибуты.

...