Instead of If/Else statements, my professor wants us to use two exceptions. Writ
ID: 3554101 • Letter: I
Question
Instead of If/Else statements, my professor wants us to use two exceptions.
Explanation / Answer
package com.sampath.chegg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
class DayException extends Exception {
String message = null;
public DayException() {
super();
}
public DayException(String message) {
super(message);
this.message = message;
}
public DayException(Throwable clause) {
super(clause);
}
public String toString() {
return message;
}
public String getMessage() {
return message;
}
}
class MonthException extends Exception {
String message = null;
public MonthException() {
super();
}
public MonthException(String message) {
super(message);
this.message = message;
}
public MonthException(Throwable clause) {
super(clause);
}
public String toString() {
return message;
}
public String getMessage() {
return message;
}
}
public class DateConversion {
public static void main(String[] args) throws IOException, ParseException, DayException, NumberFormatException, MonthException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String date = null;
System.out.print("Enter date:");
while((date=reader.readLine())!=null){
int days;
String mnthDate[] = date.split("/");
String month = checkMonth(Integer.parseInt(mnthDate[0]));
days = checkDate(Integer.parseInt(mnthDate[0]),Integer.parseInt(mnthDate[1]));
System.out.format("%s%5d ", month,days);
System.out.print("Enter date:");
}
}
private static String checkMonth(int month) throws MonthException {
String formattedDate = null;
if(month<1 || month>12)
throw new MonthException("Your Entered month is wrong");
else{
SimpleDateFormat sdf1 = new SimpleDateFormat("MMMM");
Date d = new Date(2000, month-1, 1);
formattedDate = sdf1.format(d);
}
return formattedDate;
}
private static int checkDate(int month,int date) throws DayException {
Calendar cal = Calendar.getInstance();
cal.set(2014,month-1 , 1);
int days = cal.getActualMaximum(cal.DAY_OF_MONTH);
if(date<1 || days<date)
throw new DayException("Your Entered day is wrong");
return date;
}
}