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?