So I am trying to set leapyear to true in the if statement, but when I do so it tells me thatleapYear in the second if-Statement is not Initilized. Thanks for your help!
public class LeapYear {
public static void main(String[] args) {
int year = 1600 (int)(Math.random() * 500);
final boolean leapYear;
if(year%4==0){
leapYear = true;
}
if (leapYear){
System.out.println(year " leap");
} else {
System.out.println(year " notleap");
}
}
}
CodePudding user response:
If we declare a final
variable outside an if
-else
-statement and initialize it in the if
-branch, we have to initialize it in the corresponding else
-branch as well. If no else
-branch exists, we must create one, otherwise the variable is uninitialized iff. the if
-branch is not entered.
class Ideone {
public static void main(String[] args) {
int year = 1600 (int)(Math.random() * 500);
final boolean leapYear;
if(year%4==0){
leapYear = true;
} else {
leapYear = false;
}
if (leapYear){
System.out.println(year " leap");
} else {
System.out.println(year " notleap");
}
}
}
CodePudding user response:
leap Year variable may not always be initialized
public class LeapYear {
public static void main(String[] args) {
int year = 1600 (int)(Math.random() * 500);
boolean leapYear = false;
if(year%4==0){
leapYear = true;
}
if (leapYear){
System.out.println(year " leap");
} else {
System.out.println(year " notleap");
}
}
}
CodePudding user response:
public class LeapYear {
public static void main(String[] args) {
int year = 1600 (int)(Math.random() * 500);
boolean leapYear = year % 4 == 0;
if (leapYear){
System.out.println(year " leap");
} else {
System.out.println(year " notleap");
}
}
}
CodePudding user response:
You have to remove final before the name of the variable and initialize the variable to false
for Example
public static void main(String[] args) {
int year = 1600 (int)(Math.random() * 500);
boolean leapYear = false;
if(year%4==0){
leapYear = true;
}
if (leapYear){
System.out.println(year " leap");
} else {
System.out.println(year " notleap");
}
}