2014-02-25 52 views
0

有一個名爲「約會」的類,其中3個對象需要定義。實現3維稀疏表的構造函數

這是怎麼類最初給出:

/*You must complete this class such that it can be used as nodes in a 3D sparse table.*/ 
public class Appointment 
{ 
    public Appointment() 
    { 
    /*You may implement this constructor to suit your needs, or you may add additional constructors.*/ 
    } 

    public Appointment back;//The next appointment (back) of this appointment on the same date 
    public Appointment right;//The next appointment (right) of this appointment in the same week. 
    public Appointment down;//The next appointment (down) of this appointment in the same month. 

    //Appointment particulars: 
    private String description;//A description for this appointment. 
    private int duration;//The number of hours that the appointment will last. 
} 

還有其他功能,這並不重要。

This is an image of how the 3D sparse table they want

所以我的想法是創建一個新的方法來初始化每個對象(不確定是不是我的權利!)

public Appointment() 
{ 

     right.appointmentRight(); 
} 

    public void appointmentRight() 
    { 
     for(int i=0; i<12; i++) 
     { 
     right = new Appointment(); //trying to initialize them for 12 months 

     } 
    } 

誰能給我解釋一下,如果我在正確的軌道很,或者我必須做一些完全不同的事情 謝謝

回答

0

我看到的第一件事是當你調用'right.appointmentRight();'對象'right'尚未初始化。

但是,如果你初始化它,你會有一些麻煩。你構造函數調用一個名爲appointmentRight()的函數,它調用構造函數,調用appointmentRight()...是的,無限循環。另外,在FOR循環的每次迭代中,都會擦除舊的「正確」值。

您可以添加一些其它附加的構造類似以下:

public Appointment(Appointment back) { 
    this.back = back; 
} 

根據您的問題,您也可以有更多有具體的構造函數,如:

public Appointment(Appointment back, boolean isRight, boolean isDown) { 
    this.back = back; 
    if (isRight) 
     back.setRight(this); 
    if (isDown) 
     back.setDown(this); 
} 

private void setRight(Appointment right) { 
    this.right = right; 
} 

private void setDown(Appointment down) { 
    this.down = down; 
}