Variable may not have been initialized
Hello and good afternoon.
I have just begun learning java a few days ago so apologies if this is a very dumb question. So I was doing the following program and when I it I got the error the variable (monthdays) may not have been initialized. Thereafter I decided to assign it a value of 0 and the program worked. When I researched the net I realized that the problem had something to do with local and class variables unfortunately I couldn't exactly understand how it came about. Can someone please explain in laymen terms why the error message came about. Thanks for your help and have a good day.
Code:
class MonthDaysAssignment
{
public static void main (String Args[])
{
int monthnum = 2;
int yearnum = 2001;
int monthdays =0; //variable monthdays initialized
switch (monthnum)
{
case 1: case 3: case 5: case 7: case 8: case 10: case 12: monthdays = 31;
break;
case 4: case 6: case 9: case 11: monthdays =30;
break;
}
if (yearnum%4==0)
{
monthdays = 29;
}
else if (yearnum%4!=0)
{
monthdays = 28;
}
{
System.out.println (monthdays+" days");
}
}
}
P.S. The problem was in line 7
Re: Variable may not have been initialized
It would help if your indentation was correct, but if you don't initialise monthdays with a value then there is a route through your code in which monthdays might not get set. Since the println statement at the end tries to use monthdays, then it would be possible for the code to get there without a valid value in that variable. This is not allowed by the compiler.
One way around it would be to change the case statement to have a default fall-through representing, say, the 30 day months or the 31 day ones. That way you know it has to be set. Actually, not sure your logic for February is correct, but it's hard to tell with the current layout.