Aurimas Balciunas Aurimas Balciunas - 1 month ago 14
Java Question

Cannot find my mistake, getting compilation error

I am doing this project for my Computer Science class and I've spent the better part of two hours trying to find the error in this project which uses many if(){} statements. If I delete the last bracket, then the last variable (leapyear) doesn't end up getting declared, but if I keep it, I get a compilation error.

I can't find anything wrong with what I'm done so far, so I'm only left with thinking that perhaps I've made a mistake I don't know about which causes problems in Java.

//beginning of project 5
if (projectInt == 5) {
Double leapYear;
if (leapYear %4 == 0) {
if (leapYear %100 != 0)
System.out.println("It's a leapyear!");

else if (leapYear%100 == 0) {
if (leapYear%400 == 0) {
System.out.println("It's a leapyear!");
}
else {
System.out.println("It's not a leapyear!");
}
}
}

else {
System.out.println("It's not a leapyear!");
}
} //end of project 5

}
}


Am I missing a bracket somehwere? Do I have an extra one?

This is the last part of a 5 project (all in one document) project, so if that's relevant I can post the rest of the code.

Answer

Ok I cheated and pasted your code into my currently open IDE. In Java there is a difference between default initialization on the class and local level. While class fields get a default value, local variables do not.

//beginning of project 5
  if (projectInt == 5) {
   Double leapYear;
   if (leapYear %4 == 0) {

Your leapYear is not initialized. You have to assign it a value.