0

CD の ArrayList の Band オブジェクトの ArrayList メンバ フィールドに CD オブジェクトを追加しようとしています。band_index は、コンボボックスから選択されたときの Band ArrayList のインデックスであり、band_index が選択したバンドの正しいインデックスを割り当てることを確認しました。band.get(band_index).addCD(cd);現在のバンドの addCD メソッドを呼び出すと、このコード行で Null Pointer Exception が発生します。

メインクラス:

public void addCD() {
    CD cd = new CD(t, y);

    band.get(band_index).addCD(cd); //NULL pointer Exception on this line
            updateCDs();
}

//Method to print out all the CDs of a band
public void updateCDs() {
    String list = "";
    for(int i = 0; i < band.size(); i++)
    {
          //band_index is the index of the selected band in the combobox    
          if(i == band_index) {
            for(int j = 0; j < band.get(i).getCDs().size(); j++) {
                list += "Title: " + band.get(i).getCDs().get(j).getTitle();
                list += "Year: " + band.get(i).getCDs().get(j).getYear();
            }
        }
    }
    System.out.println(list);
}

バンドクラス:

private ArrayList<CD> cds;

public void addCD(CD cd) {
    cds.add(cd);
}

CD クラス:

private String title;
private int year;

public CD(String t, int y) {
    title = t;
    year = y;
}

public getTitle() { return title; }
public getYear() { return year; }
4

1 に答える 1