Question: 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.
To run the application save both files with the same name as the class (because it is a public class) and with the .java file extension (in this case Date.java and DateTest.java). Then compile both classes and run DateTest. Date will not run because it does not have a main method.
To compile both classes at the same time using the command prompt, use the command
javac Date.java
javac DateTest.java
To run DateTest, use the command
java DateTest
1 2 |
/**<br /> *<br /> * @Author: Aghatise Osazuwa<br /> * Website: www.cscprogrammingtutorials.com<br /> *<br /> * Exercise 3.15 - Date Class<br /> * This Program Display Date In The Format mm/dd/yy<br /> *<br /> */ <br /><br />public class Date {<br /><br /> private int monthdate;<br /> private int daydate;<br /> private int yeardate;<br /> <br /> public Date (int month, int day, int year) {<br /> monthdate = month;<br /> daydate = day;<br /> yeardate = year;<br /> }<br /> <br /> public void setMonth (int month) {<br /> monthdate = month;<br /> }<br /> <br /> public int getMonth() {<br /> return monthdate;<br /> }<br /> <br /> public void setday (int day) {<br /> daydate = day;<br /> }<br /> <br /> public int getDay() {<br /> return daydate;<br /> }<br /> <br /> public void setYear (int year ) {<br /> yeardate = year;<br /> }<br /> <br /> public int getYear() {<br /> return yeardate;<br /> }<br /> <br /> public void displayDate () {<br /> System.out.printf ("%d/%d/%dn", getMonth(), getDay(), getYear());<br /> }<br /><br />}<br /> |
Below is Class DateTest.java to test Class Date.java
1 2 |
//Exercise 3.15 - Date Class Test<br />//This Program Demonstrates Class Date Capabilities<br /><br />import java.util.Scanner;<br /><br />public class DateTest {<br /> public static void main (String [] args) {<br /> <br /> Date display = new Date (0,0,0);<br /><br /> Scanner input = new Scanner (System.in);<br /> <br /> int month;<br /> int day;<br /> int year;<br /> <br /> System.out.print ("Enter Month: ");<br /> month = input.nextInt();<br /> display.setMonth(month);<br /> <br /> System.out.println ();<br /> <br /> System.out.print ("Enter Day: ");<br /> day = input.nextInt();<br /> display.setday(day);<br /> <br /> System.out.println ();<br /> <br /> System.out.print ("Enter Year: ");<br /> year = input.nextInt();<br /> display.setYear(year);<br /> <br /> System.out.println ();<br /> <br /> display.displayDate();<br /><br /> }<br />}<br /> |
1 Comment
thank you so much