Date: Wednesday, April 8, 2020.
Due date: Wednesday, April 15, 2020.
Objective: To write the switch instruction and static class attributes in Java.
In this project we will input a number from the user, representing a month of the year, then output its name and number of days.
Create a Java project in Eclipse and call it lab10. Create a class in this project called Month and containing the main method. Write your name, course, semester, and homework number at the top as a comment.
a. Scanner
Add the code for the definition of a scanner, but make it a static class attribute instead of a variable in the main. The slides contain an example of how to do this.
b. Month Name
Write a method that takes in a month number between 1 and 12 and returns a string that represents their name. Use a switch statement for this purpose. The header of this function should be
static String monthName(int n)
Implement this method using a switch statement, with a case for each of the numbers from 1 to 12, returning the month name for each of them.
In the main, declare a variable to hold the month number. Input this number from the user, then call the method monthName and output the result.
c. Number of Days
Write a method taking in a parameter that is a month name and returning the number of days in that month. The functions should also take a second boolean parameter that tells us if the year is leap or not, since the number of days in February is different in that case. The header of the method should be:
static int numberOfDays(String month, boolean isLeapYear)
Implement this method using another switch statement, where you lump together all the cases for which the number of days are the same. For the month of February (2), use a conditional in that case where you check the value of the second parameter and if it's true, return 29, otherwise 28.
Add a test for this function in the main. After you get the name of the month as a string from the first function, assuming that you stored the answer in a variable, use it to call the second function and then output the result.
d. Month Loop
Write another method where you output all the names of the months that end in "y", or just contain a "y". The header of the function should be
static void monthsInY()
In the function, use a for loop with a variable going from 1 to 12 (including). For each number, get the name of the month by calling the function monthName and for each of them, use the method contains from the class String (you can call it from a String variable) to check if the name contains the substring "y". If it does, then output the name.
Call this function from the main to make sure it works.
Run the program to make sure everything works correctly.
Upload Month.java to Canvas in Assignments - Homework 10, or wait until you have completed the homework to upload both files at the same time.