错误"The operator * is undefined for the argument type(s) int, Box"



所以我不知道为什么vol和boxes[I]没有相乘,我试图得到我已经做过的盒子的尺寸和每个盒子的体积使用循环,因为某种原因需要在box类中根据我的教授

public class Main {
public static void main(String[] args) {
Box[] boxes = new Box[5];
boxes[0] = new Box(2.5, 1.2, 2);
boxes[1] = new Box(1.5, 1.2, 2);
boxes[2] = new Box(2.5, 1.2, 0.5);
boxes[3] = new Box(3.5, 2.1, 0.3);

for (int i = 0; i < boxes.length - 1; i++) {
System.out.println("The dimensions of box " + (i + 1) + 
" is..n" +  boxes[i]);
}
Box.volume(boxes);
}
}

public class Box {
private double length;
private double width;
private double height;

Box(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
public String toString() {
return "l: " + length + "n" + "w: "+ width + "n" + "h: " + height;
}


//SETTERS AND GETTERS
public void setLength(double length) {
this.length = length;
}
public double getLength() {
return length;
}
public void setWidth(double width) {
this.width = width;
}
public double getWidth() {
return width;
}
public void setHeight(double height) {
this.height = height;
}
public double getHeight() {
return height;
}

public static void volume(Box[] boxes) {
int vol = 1;
for (int i = 0; i < boxes.length - 1; i++) {
//vol = vol * boxes[i];
}

System.out.println(vol);
}   
}

对于实参类型int, Box

,操作符*未定义。

需要实现一个实例方法boxVolume()来计算特定盒子的体积,然后需要在静态方法volume中调用该方法:

// class Box
public double boxVolume() {
return this.length * this.width * this.height;
}
public static double volume(Box[] boxes) {
double total = 0.0;
// use for each loop to iterate boxes array
for (Box box : boxes) {
if (null != box) {
total += box.boxVolume();
}
}
return total;
}

相关内容

最新更新