Exercise 05: Date Class

Date completed: 25/09/2017

Create a class called Date that includes three instance variables — a month (type int), a day (type int) and a year (type int). Provide a constructor that initializes the three instance variables and assumes that the values provided are correct. Provide a set and a get method for each instance variable. Provide a method displayDate that displays the month, day and year separated by forward slashes (/). Write a test application named DateTest that demonstrates class Date’s capabilities.

The Created Code: Date.java

                
package date;

public class Date {
    // Declaration of instance variables 
    private int day;
    private int month;
    private int year;
    
    // constructor initializes  with no arguments
    // constructor name is class name
     public Date(){
     }
     
    // constructor initializes Employee with  arguments
    // constructor name is class name
    public Date(int day, int month, int year){
        //  initialize the variables
    	this.day = day;
    	this. month = month;
        this.year = year;
    }// end constructor  

    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(){
        // these statements call the get methods
        System.out.printf( "\nToday's date is " + getDay() + "/" + getMonth() + "/" + getYear());
    } 
}   
                
            

The Code: DateTest.java

                
package date;

import java.util.Scanner;

import date.Date;

public class DateTest {

    public static void main(String[] args) {
        // create Scanner to obtain input from command window
        Scanner input = new Scanner(System.in);
        int day, month, year; 
	      
        // create two Employee object
        Date date = new Date(); 

        // ask user to input the details
        System.out.println( "\nEnter today's date.");
        System.out.printf( "Enter today's day: ");
        day = input.nextInt();			// obtain user input
        date.setDay(day); 
        System.out.printf( "Enter today's month: ");
        month = input.nextInt();		// obtain user input
        date.setMonth(month);
        System.out.printf( "Enter today's year: ");
        year = input.nextInt();			// obtain user input
        date.setYear(year);
		
        // display the date
        date.displayDate();
		
        // close the Scanner
        input.close();
    }
}
                
            

Some screen prints

Description Screen Print Out
The output as seen in Eclipse. s02ex05 image