I have a homework assignment which asks to have the user input a date in Java in the (mm/dd/yyyy) format, then to determine if the entered date is valid. I have been able to successfully do this for every month, save February, because you must take leap years into account.
I have this code:
import java.util.Scanner;
/**
*
* @author Andrew De Forest
* @version v1.0
*
*/
public class exc6
{
public static void main (String[] args)
{
//Initialize a string
String getInput;
//Initialize some integers
int month, day, year;
//Make a boolean
boolean validDate;
//Set the date to false
validDate = false;
//Ask for input
System.out.println("Enter a date (mm/dd/yyyy)");
//Initialize the scanner
Scanner keyboard = new Scanner (System.in);
//Get input & use a delimiter
keyboard.useDelimiter("[/\n]");
month = keyboard.nextInt();
day = keyboard.nextInt();
year = keyboard.nextInt();
if((month >= 1 && month <= 12) && (day >= 1 && day <= 31))
{
//For months with 30 days
if((month == 4 || month == 6 || month == 9 || month == 11) && (day <= 30))
{
validDate = true;
}
//For months with 31 days
if((month == 1 || month == 2 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day <= 31))
{
validDate = true;
}
//For February
if((month == 2) && (day < 30))
{
//Boolean for valid leap year
boolean validLeapYear = false;
//A leap year is any year that is divisible by 4 but not divisible by 100 unless it is also divisible by 400
if((year % 400 == 0) || ((year % 4 == 0) && (year %100 !=0)))
{
validLeapYear = true;
}
if (validLeapYear == true && day <= 29)
{
validDate = true;
}
else if (validLeapYear == false && day <= 28)
{
validDate = true;
}
}
}
//If the date is valid
if(validDate == true)
{
System.out.println(month + "/" + day + "/" + year + " is a valid date.");
}
else
{
System.out.println("Invalid date!");
}
}
}
The part I'm most concerned with is this:
//For February
if((month == 2) && (day < 30))
{
//Boolean for valid leap year
boolean validLeapYear = false;
//A leap year is any year that is divisible by 4 but not divisible by 100 unless it is also divisible by 400
if((year % 400 == 0) || ((year % 4 == 0) && (year %100 !=0)))
{
validLeapYear = true;
}
if (validLeapYear == true && day <= 29)
{
validDate = true;
}
else if (validLeapYear == false && day <= 28)
{
validDate = true;
}
}
}
As far as I can tell, it looks correct. However, when I input something like 2/29/2011, it returns as a valid date (which it should not, as 2011 was not a leap year). Why is this? What am I missing, or passing over, that causes bad dates to return valid?
java.util.Calendar,org.joda.time.DateTime??