Edwards
Edwards

Reputation: 105

Why won't the value of my int change?

Hi I'm fairly new to java and I am working on code that works as a calendar. I thought I had completed it but the days seem to remain as 31 rather than changing based on the if/else statement. Here is the code:

public int maxDaysInMonth( int year, int month )
{

boolean A = (year % 4 == 0) || ((year%4==0) && (year % 100 != 0));

int days = 0;
int iMonth = 0;

 if( iMonth == 4 || iMonth == 6 || iMonth == 9 || iMonth == 11)
{
    days = 30;
}

else if ( iMonth == 1 || iMonth == 3 || iMonth == 5 || iMonth == 7 || iMonth == 8 || iMonth == 10 || iMonth == 12)
{
    days = 31;
}

if (A == true && iMonth == 2)
{ 
    days = 29; 
}
else if (A == false && iMonth == 2)
{
    days = 28;
}

return days;

}

Any help is greatly appreciated!

Upvotes: 1

Views: 56

Answers (3)

DoubleMa
DoubleMa

Reputation: 368

Like other has mentioned your problem is with iMonth

Try using a simple similar code :

public int maxDaysInMonth(int year, int month) {
    int days;
    switch (month) {
        case 2:
            boolean A = (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0));
            days = A ? 29 : 28;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            days = 30;
            break;
        default:
            days = 31;
    }
    return days;
}

Upvotes: 0

Razib
Razib

Reputation: 11153

Possible Solutions:

1. Replace all iMonth with month - the variable you provided by method parameter.

2. Call the maxDaysInMonth( int year, int month ) method like this -

maxDaysInMonth( 2015, 1); // for January  
maxDaysInMonth( 2015, 2); // for February
maxDaysInMonth( 2015, 11); //for December

Upvotes: 0

rgettman
rgettman

Reputation: 178253

What's the purpose of iMonth? You initialize it to 0 then test it as if it already represented a month.

You don't need iMonth; just use month in your if tests.

Also, your leap year determination isn't quite correct. It's always a leap year if the year number is divisible by 400. Try

boolean A = (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0));

You also might want a more descriptive variable name, such as isALeapYear.

Upvotes: 1

Related Questions