PDA

Click to See Complete Forum and Search --> : Date Validation


tmoney04
Oct 11th, 2006, 03:12 PM
// ****************************************************************
// Dates.java
//
// Determine whether a 2nd-millenium date entered by the user
// is valid
// ****************************************************************
import java.util.Scanner;

public class Dates
{
public static void main(String[] args)
{
int month, day, year; //date read in from user
int daysInMonth = 31; //number of days in month read in
boolean monthValid, yearValid = false, dayValid; //true if input from user is valid
boolean leapYear = false; //true if user's year is a leap year

Scanner scan = new Scanner(System.in);

//Get integer month, day, and year from user
System.out.println("Enter a month, day, and year");
month = scan.nextInt();
day = scan.nextInt();
year = scan.nextInt();

//Check to see if month is valid

if (month <=12 && month >=1)
monthValid = true;
else
monthValid = false;
//Check to see if year is valid
if (year <=1999 && year >=1752)
//Determine whether it's a leap year
if (year % 400 == 0)
leapYear = true;
else
if (year % 4 == 0 && !((year % 100) == 0))
leapYear = true;
else
leapYear = false;

//Determine number of days in month september 9, april4 , june 6, & november 11 those have 30; all the rest are
// 31 except for February. Feb2 has 28 or 29 days.
if (month == 9 || month == 4 || month == 6 || month == 11)
daysInMonth = 30;
else
if (month == 2)
{
if (leapYear == true)
daysInMonth = 29;
if (leapYear == false)
daysInMonth = 28;
}
else
daysInMonth = 31;

//User number of days in month to check to see if day is valid
if (day <= daysInMonth)
dayValid = true;
else
dayValid = false;

//Determine whether date is valid and print appropriate message
if (monthValid == true && dayValid == true && yearValid == true)
{
System.out.println("The date is valid");
if (leapYear == true)
System.out.println("This is a leap year");
else
System.out.println("This is not a leap year");
}
else
System.out.println("The date is not valid");
}
}

vagabon
Oct 11th, 2006, 03:55 PM
use code tags

ComputerJy
Oct 12th, 2006, 11:31 AM
I don't know if you noticed, but in your code "yearValid" will always be "False"

eranga262154
Oct 24th, 2006, 01:05 AM
I don't know if you noticed, but in your code "yearValid" will always be "False"

Correct :thumb:

I'm not an expert in Java. But I'm confusing with "yearValid". As you say all the time it is False.