Can anybody tell me why the date prints 0/0/0
?
What part of the code is missing so the values input using Scanner are passed into the method DisplayDate
and printed on the screen?
import java.util.Scanner;
public class DateClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter day:");
int day = scanner.nextInt();
System.out.println("Enter month:");
int month = scanner.nextInt();
System.out.println("Enter year:");
int year = scanner.nextInt();
Date d = new Date(day,month,year);
d.DisplayDate();
}
}
class Date {
private int day;
private int month;
private int year;
public Date(int day, int month, int year) {
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public void DisplayDate() {
System.out.println(getDay() + "/" + getMonth() + "/" + getYear());
}
}
This is the problem:
public Date(int day, int month, int year) {
}
Your constructor completely ignores its parameters, leaving your fields with their default values. For int
fields, that's 0.
Instead, it should save the values, e.g.
public Date(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
or perhaps call your properties:
public Date(int day, int month, int year) {
setDay(day);
setMonth(month);
setYear(year);
}
I'd also strongly recommend that:
DisplayDate
to displayDate
, or separate the concern of formatting from writing to the console, by just overriding toString
instead)See more on this question at Stackoverflow