write exception classes for the following error conditions: A number less than 1
ID: 3567661 • Letter: W
Question
write exception classes for the following error conditions: A number less than 1 or greater than 12 is given for the month number. The only valid options for the month number are: 1,2,3,4,5,6,7,8,9,10,11,12. (Class Name- InvalidMonthNumberException.java)
An invalid string is given for the name of the month. The only valid options for the months are: January, February, March, April, May, June, July, August, September, October, November, and December. (Class Name- InvalidMonthNameException.java)
Modify the Month class so it throws the appropriate exception when either of these errors occurs. All the constructors (Month) and methods that are setting values for the month (SetMonthNumber, SetMonthName) should throw exceptions of that particular invalid month type (InvalidMonthNumberException, InvalidMonthNameException).
Create a program/project called Assignment 10 in the same project as the Month.java. You will need to add the class Month to the project and add your code to the project class main method.
Explanation / Answer
import java.util.Scanner;
public class InvalidMonthNumberException {
public static void main(String[] args)
{
// Declare and instantiate a Scanner object for user input
Scanner keyboard = new Scanner(System.in);
// Declare a Month object to test program
Month nextMonth;
// Prompt for month and read from user
System.out.print("Enter a month (either 1..12, a month name, or quit to stop): ");
String userInput = keyboard.nextLine();
// Keep looping until the user wants to quit
while (!userInput.equalsIgnoreCase("quit"))
{
try
{
try
{
// try to accept month as an integer value
int monthNumber = Integer.parseInt(userInput);
nextMonth = new Month(monthNumber);
System.out.println("Created month " +
nextMonth.getMonthName() + " as " +
nextMonth.getMonthName());
}
catch (NumberFormatException e)
{
// Month not valid integer, process as month name
nextMonth = new Month(userInput);
System.out.println("Created month " +
nextMonth.getMonthName() + " as " +
nextMonth.getMonthName());
}
}
catch (InvalidMonthNumberException e)
{
System.out.println(e.getMessage());
}
catch (InvalidMonthNumberException e)
{
System.out.println(e.getMessage());
}
// Prompt for and read in next month
System.out.print(" Enter a month (either 1..12, a month name, or quit to stop): ");
userInput = keyboard.nextLine();
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.