Java to code : \"Return Within 30 Days for a Full Refund\" Your final solution w
ID: 3758255 • Letter: J
Question
Java to code : "Return Within 30 Days for a Full Refund"
Your final solution will have 3 files (there are 3 classes) so you will need to bundle them together into 1 compressed file. Please submit either a .zip file or a .jar file, named LastNameHW4.
Most return policies give a window of time from the date of purchase, for example 30 days. But how do you find a future date from a given date? Let's write a tool to figure this out.
Objectives
Defining your own object to a specification
Write both supplier and client code
Working with multiple classes and starter code
Specification
This assignment has 2 parts. In part 1, you'll implement a class to a given specification. In part 2, you'll modify starter code to complete a stand-alone program using the class you wrote in part 1.
Part 1:
You are going to write a class named Date with the following class specification:
The year must be 1600 or later
The day must be legal for the month
The day and month must be legal for the year
For example, if the month is June, the day should never be 31. If the month is February, the day can only be 29 if it is a leap year. All methods that affect the state of a Date object must ensure this.
Determining a leap year:
A year is a leap year if it is divisible by 4, except if it is divisible by 100. If a year is divisible by 100, then it must be divisible by 400 to be a leap year. For example, the following are leap years: 1976, 1600, and 2000. 1982 and 1900 are not leap years.
Part 2:
To complete the program, you first need to download the starter code. This code creates a graphical user interface that allows the user to interact with the program. To start the program, compile the given files, then choose the main() method from the FindADate class. You should see a window open with some text, a button, and 3 ways to enter input. Choose values and then hit the enter key (read the instructions for more details). It should display a message to System.out. If you've gotten this far then you know that the starter code works.
Your task is to modify the FindADate class so that it gets the input from the user and displays the correct result to the GUI window. The class that controls the GUI window is the UserWindow class; FindADate class will be a client of the UserWindow class. I recommend opening UserWindow to the interface view. FindADate is also a client of your Date class so make sure you've tested it well.
Though the user interface restricts user input well, there is still the chance that the input is invalid. Make sure your client code calls isLegal() before trying to construct or update a Date object. We don't know yet how to "recover" from a thrown exception. If FindADate determines that the input is invalid, have it display an error message to the user, using the error window method in UserWindow.
Starter code
FindADate.java
/**
* Top-level client -- controls the application. This GUI program prompts
* the user for a date in the form mm/dd/yyyy and then determines the date
* 30 days in the future.
* <br>
* This is the file you need to modify to complete the assignment. The majority
* of your work will be in the method respondToUser(), though you may decide
* to add code in other places as well
* <br>
* To start the program, call the main() method.
*
* @author CSC 142
* @version 1-23-07
*/
public class FindADate
{
private UserWindow window;
/**
* Create a new FindADate object
*/
public FindADate( ) {
window = new UserWindow(this);
}
/**
* Perform the task of determining 30 days from the given day.
*/
public void respondToUser()
{
System.out.println("You've downloaded and compiled correctly");
}
// NO NEED TO CHANGE ANY CODE BELOW THIS LINE.
/**
* Allows this application to be run as a stand-alone program, and
* also starts it up in a 'thread-safe" way.
*/
public static void main( String[] args ) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
FindADate pa = new FindADate( );
}
});
}
}
UserWindow.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* Creates the graphical user interface for the program FindADate.
*
* DO NOT MODIFY THIS CODE. Feel free to read through it if you'd like. I'd be happy to
* discuss it with anyone via email or the message board.
*
* @author CSC 142
* @version 1-23-07
*/
public class UserWindow {
private FindADate owner;
// private JTextField startDay, startMonth, startYear;
private JSpinner startDay, startMonth, startYear;
private JButton timeTravel;
private JLabel displayArea;
private static final String[] MONTHS = {"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"};
/**
* Construct a new user interface for the FindADate program.
* @param source object that starts the program and responds to user input.
*/
public UserWindow(FindADate source ) {
owner = source;
createAndShowGUI( );
}
/**
* Replace existing data in the display area with the String value
* provided.
* @param text the text to be shown
*/
public void displayText( String text ) {
displayArea.setText( text );
}
/**
* Display an error pop-up window with the given text
* @param text the text to be displayed in the error window
*/
public void displayErrorWindow(String text) {
JOptionPane.showMessageDialog(null, text, "Invalid Input", JOptionPane.ERROR_MESSAGE);
}
/**
* Returns the day selected by the user.
* @return the value from the day spinner
*/
public int getDayInput( ) {
return ((Integer)startDay.getValue()).intValue();
}
/**
* Returns the name of the month selected by the user
* @return the value from the month spinner
*/
public String getMonthInput( ) {
return ((String)startMonth.getValue());
}
/**
* Returns the year selected by the user.
* @return the value from the year spinner
*/
public int getYearInput( ) {
return ((Integer)startYear.getValue()).intValue();
}
private void createAndShowGUI( ) {
// create and show entire display
JFrame win = new JFrame( );
win.setSize(400, 300);
JPanel mainPanel = createMainPanel( );
win.getContentPane().add( mainPanel, BorderLayout.CENTER );
win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
win.setTitle( "Find Me a Date!" );
win. validate( );
win.setVisible( true );
win.toFront();
}
private JPanel createMainPanel( ) {
Dimension d = new Dimension(80, 20); // for the JLabels to line up
Dimension d2 = new Dimension(100,20);
Color c = new Color(153, 255, 153); //a pale green
Color back = Color.blue;
// 3 JSpinners for input
startDay = new JSpinner(new SpinnerNumberModel(1, 1, 31, 1));
SpinnerListModel m = new SpinnerListModel(MONTHS);
startMonth = new JSpinner(m);
// make it wider
//Tweak the spinner's formatted text field.
JFormattedTextField ftf = getTextField(startMonth);
if (ftf != null ) {
ftf.setColumns(6); //specify more width than we need
ftf.setHorizontalAlignment(JTextField.CENTER);
}
startYear = new JSpinner(new SpinnerNumberModel(2000, 1950, 2050, 1));
//Make the year be formatted without a thousands separator.
startYear.setEditor(new JSpinner.NumberEditor(startYear, "#"));
// 3 labels
JLabel dayLabel = new JLabel( " Day " );
dayLabel.setHorizontalAlignment(SwingConstants.CENTER);
dayLabel.setPreferredSize(d);
dayLabel.setOpaque(true);
dayLabel.setBackground(c);
JLabel monthLabel = new JLabel("Month");
monthLabel.setHorizontalAlignment(SwingConstants.CENTER);
monthLabel.setPreferredSize(d);
monthLabel.setOpaque(true);
monthLabel.setBackground(c);
JLabel yearLabel = new JLabel("Year");
yearLabel.setHorizontalAlignment(SwingConstants.CENTER);
yearLabel.setPreferredSize(d);
yearLabel.setOpaque(true);
yearLabel.setBackground(c);
// bundle label/spinners
JPanel dayPanel = new JPanel( );
dayPanel.add( dayLabel );
dayPanel.add( startDay);
dayPanel.setBackground(back);
JPanel monthPanel = new JPanel( );
monthPanel.add( monthLabel );
monthPanel.add( startMonth);
monthPanel.setBackground(back);
JPanel yearPanel = new JPanel( );
yearPanel.add( yearLabel );
yearPanel.add( startYear);
yearPanel.setBackground(back);
// create display label and area
JButton result = new JButton("Date in 30 days" );
result.addActionListener(new GoListener());
displayArea = new JLabel();
displayArea.setOpaque(true);
displayArea.setBackground(Color.white);
displayArea.setPreferredSize(d2);
//bundle these 2 up
JPanel bottomPanel = new JPanel();
bottomPanel.add(result);
bottomPanel.add(displayArea);
bottomPanel.setBackground(back);
// bundle both input area and display area
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
controlPanel.add(monthPanel);
controlPanel.add(dayPanel);
controlPanel.add(yearPanel);
controlPanel.add(bottomPanel);
controlPanel.setBackground(back);
return controlPanel;
}
/**
* Return the formatted text field used by the editor, or
* null if the editor doesn't descend from JSpinner.DefaultEditor.
*/
private JFormattedTextField getTextField(JSpinner spinner) {
JComponent editor = spinner.getEditor();
if (editor instanceof JSpinner.DefaultEditor) {
return ((JSpinner.DefaultEditor)editor).getTextField();
} else {
System.err.println("Unexpected editor type: "
+ spinner.getEditor().getClass()
+ " isn't a descendant of DefaultEditor");
return null;
}
}
/* For those brave students who venture down here...
* There classes are MEMBERS of the UserWindow class, that's why the keyword private
* There are advantages to a design like this that I'd be happy to discuss
*/
private class GoListener implements ActionListener {
/* Responds to user hitting the enter key from the JTextFields
* Need to validate user input that they are ints. If so
* send control to owner.takeAction() who will test for valid date
* Otherwise, pop up error window
*/
public void actionPerformed(ActionEvent e) {
owner.respondToUser(); // callback to client
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String message = "Enter a numeric value for a day, month, and year in each box. "+
"Once you've entered all 3 numbers, hit the enter key and you will "+
"see the result. Note, the cursor must be within one of the input " +
"boxes for action to happen. " +
"You may change a value in any box and hit the enter key again for " +
"a new answer.";
JOptionPane.showMessageDialog(null, message, "Instructions", JOptionPane.INFORMATION_MESSAGE);
}
}
}
- day
- month
- year
/* Class invariants:
The year must be 1600 or later
The day must be legal for the month
The day and month must be legal for the year
For example, if the month is June, the day should never be 31. If the month is February, the day can only be 29 if it is a leap year. All methods that affect the state of a Date object must ensure this.
+ Date( int month, int day, int year ) -- construct a Date object with the given state. If any of the parameter values are invalid, throw an IllegalArgumentException. Make sure that the exception contains a message specific to the problem.
+ boolean isLegal( int month, int day, int year ) -- returns true if these 3 values make up a valid date, false otherwise. Leap years are considered.
+ int getDay() -- returns the day of this Date
+ int getMonth() -- returns the numeric value of the month of this Date
+ String getMonthName() - returns the name of the month of this Date. The name starts with a capital letter.
+ int getYear() -- returns the year of this Date
+ String toString() -- returns this Date as a String of the form: mm/dd/yyyy. An example would be 02/20/1974 or 10/11/1234
+ Date daysFromDate( int days ) -- returns a new Date that is "days" in the future from this Date. A valid parameter is in the range [1, 31]. Throw an IllegalArgumentException if the parameter is invalid.
+ void setDay( int day) -- update the day of this Date. If the parameter value is invalid, throw an IllegalArgumentException.
+ void setMonth( int mth) -- update the month of this Date. If the parameter value is invalid, throw an IllegalArgumentException.
+ void setYear( int yr) -- update the year of this Date. If the parameter value is invalid, throw an IllegalArgumentException.
Explanation / Answer
Answer:
Note: I solved the first part, class Date is implemented as per the method specification provided. Class is asked to implement that is implemented
Program code:
Answer:
Note: I solved the first part, class Date is implemented as per the method specification provided. Class is asked to implement that is implemented
Program code:
import java.util.TimeZone;
//class name date
public class Date
{
//class invariants
private static final int JANUARY = 1;
private static final int FEBRUARY = 2;
private static final int DECEMBER = 12;
private static final int DAYS_PER_WEEK = 7;
private static final int DAYS_PER_YEAR = 365;
private static final int DAYS_PER_LEAP_YEAR = 366;
private static final String[] DAY_NAMES = {"SUNDAY",
"MONDAY", "TUESDAY","WEDNESDAY", "THURSDAY", "FRIDAY",
"SATURDAY"};
private static final int[] DAYS_PER_MONTH = { -1,
};
//variables declared
private int year;
private int month;
private int day;
//constructor parameterised
public Date(int year, int month, int day)
{
this.year = year;
this.month = month;
this.day = day;
if (month < 1 || month > 12 || day < 1 || day >
daysFromDate(day))
{
//throws illegal argument exception
throw new IllegalArgumentException("Invalid day or month:" + toString());
}
}
//method Boolean islegal
public boolean isLegal( int day, int month, int year )
{
double years = year % 4;
if ( day > 31 || day < 0 )
return false;
if ( month < 0 || month > 12 )
return false;
if ( year < 1 )
return false;
if ( (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) && day > 0 && day <= 31){
return true;
}
else if ( (month==4 || month==6 || month==9 || month==11) && day > 0 && day <= 30 ){
return true;
}
else if ( year == 0 && month==2 && day > 0 && day <= 29){
return true;
}
else if ( year != 0 && month==2 && day > 0 && day <= 28){
return true;
}
else{
return false;
}
}
//constructor
public Date()
{
this(1970, JANUARY, 1);
int daysSinceEpoch = (int) ((System.currentTimeMillis() + TimeZone.getDefault().getRawOffset()) / 1000 / 60 / 60/ 24);
for (int i = 0; i < daysSinceEpoch; i++)
{
}
}
//method getDay()
public int getDay()
{
return day;
}
//method getMonth()
public int getMonth()
{
return month;
}
//method getDay()
public int getYear()
{
return year;
}
//string to string
public String toString()
{
return year + "/" + pad(month) + "/" + pad(day);
}
private String pad(int n)
{
if (n < 10)
{
return "0" + n;
}
else
{
return "" + n;
}
}
//method daysFromDate
public int daysFromDate(int days)
{
days = DAYS_PER_MONTH[month];
if (month == FEBRUARY && isLeapYear())
{
days++;
}
return days;
}
//method setDay
public void setDay(int dy)
{
dy=day;
}
//method setMonth
public void setMonth(int mth)
{
mth=month;
}
//method setYear
public void setYear(int yr)
{
yr=year;
}
//isLeapYear()
public boolean isLeapYear()
{
return (year % 400 == 0) || (year % 4 == 0 && year % 100
!= 0);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.