obonmarc obonmarc - 1 month ago 5
Java Question

How come I can't get the values to display properly?

this program is made to take the user's chosen date and the user's chosen birth date and calculate how old they are. So far I've gotten as far as getting the user to input the values and get their name. As for returning the values in the AgeCalculator class, it doesnt seem to be doing anything since when printed in main it returns my default values (2000/01/01). How can I get the values to display properly after input?

OurDate Class // Declares all variables and methods for the AgeCalculator Class below

import java.util.Scanner;

public class OurDate {

private int year;
private int month;
private int day;
private Scanner scan = new Scanner(System.in);

public OurDate() {

year = 2000;
month = 1;
day = 1;

}

public void setYearFromUser() {

System.out.print("Enter a valid year: ");
year = scan.nextInt();

}

public void setMonthFromUser() {
System.out.print("Enter the month: ");
month = scan.nextInt();

}

public void setDayFromUser() {
System.out.print("Enter the day: ");
day = scan.nextInt();
System.out.println("");

}

public void displayDate() {

System.out.println(month + "/" + day + "/" + year);

}

public int calcDays() {

return (year*360*month*30 + day);


}
}


AgeCalculator Class // Creates methods for the main file (Assign2) below

import java.util.Scanner;

public class AgeCalculator {

private OurDate todayDate;
private OurDate birthDate;
private String personName;
private String message;

public AgeCalculator() {

todayDate = new OurDate();
birthDate = new OurDate();

}

public void enterData() {

System.out.println("Enter today's date: ");
todayDate.setYearFromUser();
todayDate.setMonthFromUser();
todayDate.setDayFromUser();

System.out.println("Enter birth date: ");

birthDate.setYearFromUser();
birthDate.setMonthFromUser();
birthDate.setDayFromUser();

System.out.println("Enter person's name:");
Scanner scan = new Scanner (System.in);
personName = scan.nextLine();

}

public void calculateMessage() {



}

public void displayResults() {

System.out.print("Today date: ");
todayDate.displayDate();

System.out.print("Birth date: ");
birthDate.displayDate();

System.out.print(personName);

}
}


Assing2 Class // Main file

public class Assign2{

public static void main(String[] args) {

AgeCalculator inputFromUser = new AgeCalculator();
inputFromUser.enterData();

AgeCalculator displayMessage = new AgeCalculator();
displayMessage.displayResults();

}


}

Answer

The main functions creates 2 different objects. In Java and OOP programming languages, Each object has its own set of the data.

So inputFromUser object has acquired the right input from the user as you called enterData() on it.

and displayMessage doesn't.

You must use the same object

AgeCalculator calc = new AgeCalculator();
calc.enterData();
calc.displayResults();