简体   繁体   中英

Object in arraylist printing null

I'm trying to make a diary that stores a list of diary entries (Diary) each with a title, date and entry. These will be added, deleted and displayed by the DiaryBook class. Right now I'm just trying to test it by printing out the fields but they are all printing null. I've looked through similar questions and I still can't work out why. I'm new to java so any help/comments are appreciated.

public class DiaryBook {

ArrayList<Diary> diaryList = new ArrayList<Diary>();
static Scanner scanner = new Scanner(System.in);

public void addDiary () {
    String title;
    String content;
    Calendar date;

    String[] splitDate;

    System.out.print("Entry title: ");
    title = scanner.nextLine();

    System.out.print("Entry for date (dd/mm/yyyy): ");
    splitDate = scanner.next().split("/");
    scanner.nextLine();

    int day = Integer.parseInt(splitDate[0]);
    int month = Integer.parseInt(splitDate[1]);
    int year = Integer.parseInt(splitDate[2]);

    date = new GregorianCalendar(year,month-1,day);

    System.out.print("Entry: ");
    content = scanner.nextLine();

    Diary d = new Diary (title, date, content);
    diaryList.add(d);

}

public void printDiaries() {
    for (Diary x:diaryList) {
        x.getTitle();
        x.getDate();
        x.getContent();
    }
}

}

My Diary Class:

public class Diary {

String title;
Calendar date;
String content;

public Diary (String title, Calendar date, String content) {
    title = this.title;
    date = this.date;
    content = this.content;
}

public void getTitle() {
    System.out.println(title);
}
public void getDate() {
    System.out.println(date);
}
public void getContent() {
    System.out.println(content);
}

}

Input:

Entry title: Blah
Entry for date (dd/mm/yyyy): 22/12/1990
Entry: Something

Output:

null
null
null

Thanks.

You've assigned the wrong values to the wrong parameters...

public Diary (String title, Calendar date, String content) {
    title = this.title;
    date = this.date;
    content = this.content;
}

This is assigning the values of the instance variables to the parameters, which has no effect...

Instead, try assigning the parameters to the instance variables...

public Diary (String title, Calendar date, String content) {
    this.title = title;
    this.date = date;
    this.content = content;
}

Also, you get methods should return the value, not print them...just saying...

You are mixing up your variables. The "this" statement in java refers to the one already defined in the class while the ones without "this" refer to the ones in the parameters. So as mentioned you just need to switch them around, it's printing null because they are not declared as anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM