Mano Mano - 18 days ago 5
Java Question

How to be more efficient with error handling?

I made a program which converts days, months, and years into Julian days.

int year, month, day;

do
{
System.out.print("Enter the year ");
year = keyIn.nextInt();
if(year < 1)
{
System.out.println("Invalid year entered!");
System.out.println(" ");
}
}while(year < 1);
do
{
System.out.print("Enter the month ");
month = keyIn.nextInt();
if(month < 1 || month > 12)
{
System.out.println("Invalid month entered!");
System.out.println(" ");
}
}while(month < 1 || month > 12);
do
{
System.out.print("Enter the day ");
day = keyIn.nextInt();
if(day < 1 ||day > 31)
{
System.out.println("Invalid day entered!");
System.out.println(" ");
}
}while((month == 4 && day > 30) || (month == 2 && day > 29) || day < 1 ||day > 31);
keyIn.close();
int [] daysInAMonth = {31,28,31,30,31,30,31,31,30,31,30,31};

if(year % 4 == 0 && year % 100 != 0)
{
daysInAMonth[1] = 29;
}
else if(year%400==0 && year%100==0)
{
daysInAMonth[1] = 29;
}
else
{
daysInAMonth[1] = 28;
}
int julianDays = 0;
for (int i=0; i < month-1; i++)
{
julianDays += daysInAMonth[i];
}
julianDays += day;
System.out.println("The Julian Day is " +julianDays);


But I have ran into some issues when a user enters dates such as 31th of March 2001 (2001, 4, 31), as there are only 30 days in April.

Is there a more efficient way to handle these errors rather than trying to test everything inside a do-while loop when user enters their date?

Answer

I guess the main point of your code is learning how to do something like that. And for that purpose, it is ok.

Of course, if we would be talking "real world production" code, your code would not do:

  1. You avoid re-inventing the wheel for things that exist in standard libraries. And Java has actually several Date/Time APIs. (you would be looking at using the latest things added with Java8)
  2. You should avoid putting all this code into a single place. Instead; you could create helper methods.

Like:

private boolean isYearValid(int year) {
  return (year > 1);
}

and

private void boolean isMonthValid(...

but of course, to validate the day information you would need to pass month and year, too.

The point here is: validating dates is a complex undertaking. Thus you can't avoid putting down complex code that uses heavy if/else checking. But the point is: you should still try to make that code as readable as possible.

And many people think that having small methods with meaningful names, even simple things like:

boolean isLeapYear(int year)

will help you achieving that. So instead of cluttering your direct validation code with the code that checks if a year is leap year, you would be simply calling isLeapYear(year) instead. That doesn't make the complex checking itself go away, but you can move it outside of the context of your validation method!

Comments