2016-09-07 18 views
1

これは私の問題です。デフォルトのwoodTypeでChairオブジェクトの配列を作成する必要があります。私は配列自体を宣言できますが、明らかにすべての値がnullです。配列内の各議長オブジェクトをインスタンス化しようとすると、エラーが発生します。インスタンス化しようとしているときに何が間違っているのか分からないので、助けてください。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)。

関連する問題