我无法将数组参数传递给另一个类

时间:2016-03-18 17:54:07

标签: java

我想在矩形类中计算矩形区域,但我不能在立方体类中传递矩形区域。立方体的区域是通过在数组中添加矩形区域6次来计算的。{{3 }}

我的矩形类

public class Rectangle extends Shape {

    Scanner in = new Scanner(System.in);
    int length;
    int width;

    Rectangle(String name, String unit, int length, int width) {

        super(name, unit);
        this.length = length;
        this.width = width;

    }

    public int getwidth() {
        return this.width;
    }

    public int getlength() {
        return this.length;
    }

    public void setwidth(int width) {
        this.width = width;
    }

    public void setlength(int length) {
        this.length = length;
    }

    @Override
    public void getInput() {

    }

    @Override
    public int getArea() {
        return this.width * this.length;
    }

    @Override
    public void display() {
        super.display();
        System.out.println("length:" + this.length + "width:" + this.width);
        System.out.println("area is" + getArea());
    }

    public class Cube extends Shape {

        Rectangle[] r = new Rectangle[6];

        Boolean solid;
        String color;

        Cube(String name, String unit, Boolean solid, String color) {
            super(name, unit);
            this.solid = solid;
            this.color = color;

        }

        @Override
        public int getArea() {
            int sum = 0;
            r[0] = new Rectangle("Rectangle", "Unit1", 10, 20);
            r[1] = new Rectangle("Rectangle", "Unit2", 10, 20);
            r[2] = new Rectangle("Rectangle", "Unit3", 10, 20);
            r[3] = new Rectangle("Rectangle", "Unit4", 10, 20);
            r[4] = new Rectangle("Rectangle", "Unit5", 10, 20);
            r[5] = new Rectangle("Rectangle", "Unit6", 10, 20);
            for (int i = 0; i < r.length; i++) {
                sum = sum + r[i];

            }
            return sum;

        }

        @Override
        public void getInput() {

        }

        @Override
        public void display() {
            super.display();
            System.out.println("color:" + this.color + "solid:" + this.solid);
            System.out.println("sum of cube" + getArea());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

更新您的代码

sum= sum+r[i];

到这个

sum = sum + r[i].getArea();

基本上你已经制作了一个Rectangle的数组。如果您想获得widthlengtharea,则必须使用对象的获取者为您的int获取sum。< / p>