Skip to main content

Beginning JAVA - Having trouble

1 reply [Last post]
bballp6699
Offline
Joined: 2006-02-17

I can't see whats wrong with my code. Probably something simple, but I'm just starting. Compiler says the boolean values aren't initialized.

// ****************************************************************
// Dates.java
//
// Determine whether a 2nd-millenium date entered by the user
// is valid
//
// ****************************************************************
import cs1.Keyboard;

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

//Get integer month, day, and year from user
System.out.println ("What is the month? (1-12)");
month = Keyboard.readInt();
System.out.println ("What is the day? (1-31)");
day = Keyboard.readInt();
System.out.println ("What is the year?");
year = Keyboard.readInt();
leapYear = true;

//Check to see if month is valid
if ((month > 1) && (month < 12))
monthValid = true;

//Check to see if year is valid
if ((year < 1999) && (year > 1000))
yearValid = true;

//Determine whether it's a leap year
if ((year % 4) == 0 && ((year % 100) != 0))
daysInMonth =29;

//Determine number of days in month
if (month == 1 && month == 3 && month == 5 && month == 7 && month == 8 && month == 10 && month == 12)
daysInMonth = 31;
else
if (month == 2)
if (leapYear == true)
daysInMonth = 29;
else daysInMonth = 28;
else daysInMonth = 30;

//User number of days in month to check to see if day is valid
if (day >=1 && day <= 31)
dayValid = true;

//Determine whether date is valid and print appropriate message
if ( dayValid == true && monthValid == true && yearValid == true)
System.out.println ("Date is valid");
else
System.out.println ("Date is not valid");

}

}

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
jafaucett
Offline
Joined: 2006-02-17

You said "Compiler says the boolean values aren't initialized." And that's exactly the problem. By the time you get around to using the dayValid, etc. variables, their value may or may not have been set. If they are supposed to start out as false, then put that in the declaration.