2016-09-07 134 views
1

這是我的難點:我需要使用默認的woodType創建一個Chair對象數組。我能夠聲明數組本身,但顯然所有的值都是null。當我嘗試實例化數組中的每個Chair對象時,我遇到錯誤。我不確定在嘗試實例化時我做錯了什麼,請幫忙。在Java中創建對象數組時遇到問題

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; 
    } 
} 
+1

看起來像你的'for'循環只是在課堂上浮動。功能代碼不能去那裏。把它放在'TableSet()'構造函數中。 – Zircon

+0

您無法在方法外運行代碼。你的意思是把它放在構造函數中嗎? – shmosel

回答

0

int是Java中的簡單類型,沒有任何方法或字段。只是省略這個.length,錯誤消失了。在我看來,它已經存儲了椅子的實際數量(2)。