|
-
Oct 11th, 2006, 02:12 PM
#1
Thread Starter
New Member
Date Validation
// ****************************************************************
// 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");
}
}
-
Oct 11th, 2006, 02:55 PM
#2
Lively Member
-
Oct 12th, 2006, 10:31 AM
#3
Re: Date Validation
I don't know if you noticed, but in your code "yearValid" will always be "False"
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Oct 24th, 2006, 12:05 AM
#4
PowerPoster
Re: Date Validation
 Originally Posted by ComputerJy
I don't know if you noticed, but in your code "yearValid" will always be "False"
Correct
I'm not an expert in Java. But I'm confusing with "yearValid". As you say all the time it is False.
“victory breeds hatred, the defeated live in pain; happily the peaceful live giving up victory and defeat” - Gautama Buddha
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|