java - 在 Java 中创建对象数组时遇到问题

标签 java arrays

这是我的症结所在:我需要使用默认的 woodType 创建一个 Chair 对象数组。我可以声明数组本身,但显然所有值都是空的。当我尝试实例化数组中的每个 Chair 对象时,出现错误。我不确定在尝试实例化时我做错了什么,请帮忙。

public class PAssign3 {

public static void main(String[] args) {

    TableSet set1 = new TableSet();

    TableSet set2 = new TableSet(5, 7, 4);
//        Chair chr1 = new Chair();//this works properly, setting wood as Oak
//        Chair chr2 = new Chair("Pine");//works

    }

}

class TableSet {

    Table table = new Table();

    private int numOfChairs = 2;

    //creates an array that can hold "numOfChairs" references to same num of 
    //chair objects; does not instantiate chair objects!!!
    Chair[] chairArr = new Chair[numOfChairs];

    //instantiate each chair object for length of array
    //this loop does not work; Error: illegal start of type
    for (int i = 0; i < numOfChairs.length; i++) {
        chairArr[i] = new Chair();
        }

    public TableSet() {
    }

    public TableSet(double width, double length, int numOfChairs) {
        table = new Table(width, length);
        this.numOfChairs = numOfChairs;
        chairArr = new Chair[numOfChairs];

        //this loop also does not work; Error: int cannot be dereferenced
        for (int i = 0; i < numOfChairs.length; i++) {
            chairArr[i] = new Chair();
        }
    }

    public void setNumOfChairs(int numOfChairs) {
        this.numOfChairs = numOfChairs;
    }

    public int getNumOfChairs() {
        return numOfChairs;
    }

    public String getChairWoodType() {
        return chairArr[0].getWoodType();
    }
}

class Table {

    private double width = 6;
    private double length = 4;

    public Table() {
    }

    public Table(double width, double length) {
        this.width = width;
        this.length = length;
    }

    public void setWidth(double width) {
        this.width = (width < 0) ? 0 : width;
    }

    public void setLength(double length) {
        this.length = (length < 0) ? 0 : width;
    }

    public double getWidth() {
        return width;
    }

    public double getLength() {
        return length;
    }
}

class Chair {

    private String woodType = "Oak";

    public Chair() {
    }

    public Chair(String woodType) {
        this.woodType = woodType;
    }

    public void setWoodType(String woodType) {
        this.woodType = woodType;
    }

    public String getWoodType() {
        return woodType;
    }
}

最佳答案

int 是 Java 中的简单类型,没有任何方法或字段。只需省略此.length,错误就会消失。在我看来,它已经存储了椅子的实际数量 (2)。

关于java - 在 Java 中创建对象数组时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39375895/

相关文章:

java - 如何在Android中将波斯日期转换为公历日期

java - 你能用谷歌端点设置一个简单的登录系统吗

java - 与字符串方法 .indexOf() Java 混淆的结果

java - 如何从两个文本文件中读取数据并链接数据?

c - 理解函数原型(prototype)

arrays - FirstIndex :of: in an array of objects

java - Java中的不可变数组

javascript - 如何在 Angular 1 中将项目移动到列表前面

java - Spring-security/登录重定向

javascript - 未捕获的类型错误 : Cannot read property of 'send' undefined