java - Object in arraylist printing null -
i'm trying make diary stores list of diary entries (diary) each title, date , entry. these added, deleted , displayed diarybook class. right i'm trying test printing out fields printing null. i've looked through similar questions , still can't work out why. i'm new java help/comments 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 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() { (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 date (dd/mm/yyyy): 22/12/1990 entry:
output:
null null null
thanks.
you've assigned wrong values wrong parameters...
public diary (string title, calendar date, string content) { title = this.title; date = this.date; content = this.content; }
this assigning values of instance variables parameters, has no effect...
instead, try assigning parameters instance variables...
public diary (string title, calendar date, string content) { this.title = title; this.date = date; this.content = content; }
also, get
methods should return value, not print them...just saying...
Comments
Post a Comment