187k views
5 votes
In this lab, you add the input and output statements to a partially completed Java program. When completed, the user should be able to enter a year, a month, and a day to determine if the date is valid. Valid years are those that are greater than 0, valid months include the values 1 through 12, and valid days include the values 1 through 31.

Instructions
Notice that variables have been declared for you.
Write the simulated housekeeping() method that contains input statements to retrieve a yearString, a monthString, and a dayString from the user.
Add statements to the simulated housekeeping() method that convert the String representation of the year, month, and day to ints.
Include the output statements in the simulated endOfJob() method. The format of the output is as follows:
month/day/year is a valid date.
or
month/day/year is an invalid date.
Execute the program entering the following date:
month = 5, day = 32, year =2014
Observe the output of this program.
Execute the program entering the following date:
month = 9, day = 21, year = 2002
Observe the output of this program.

1 Answer

1 vote
Here's an example of how you can complete the program:

```java
import java.util.Scanner;

public class DateValidation {
private static int year;
private static int month;
private static int day;

public static void main(String[] args) {
housekeeping();
endOfJob();
}

public static void housekeeping() {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the year: ");
String yearString = scanner.nextLine();
year = Integer.parseInt(yearString);

System.out.print("Enter the month: ");
String monthString = scanner.nextLine();
month = Integer.parseInt(monthString);

System.out.print("Enter the day: ");
String dayString = scanner.nextLine();
day = Integer.parseInt(dayString);
}

public static void endOfJob() {
boolean isValid = isValidDate(year, month, day);

String date = month + "/" + day + "/" + year;

if (isValid) {
System.out.println(date + " is a valid date.");
} else {
System.out.println(date + " is an invalid date.");
}
}

public static boolean isValidDate(int year, int month, int day) {
if (year <= 0 || month < 1 || month > 12 || day < 1 || day > 31) {
return false;
}

// Additional validation rules can be added here if needed

return true;
}
}
```

This code defines a Java program that prompts the user to enter a year, month, and day, then checks if the entered date is valid according to the given criteria.
User Clocher Zhong
by
8.4k points

No related questions found