gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:16:25 25 4
gpt4 key购买 nike

这是我的症结所在:我需要使用默认的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com