I’m doing a course management system using java, and I want to check if a course if already enrolled.
Here is my code
boolean duplicateCheck;
for (int i=0; i<enrolledCourses.size(); i++) {
if (enrolledCourses.get(i) == searchResult.get(Integer.parseInt(userInput)-1)) {
duplicateCheck = true;
break;
} else {
duplicateCheck = false;
}
if (duplicateCheck) {
System.out.println("You've already enrolled in this course!");
} else {
...
}
But in the second if statement it says
The local variable duplicateCheck may not have been initialized
What’s wrong with my code? What should I do to fix it?
>Solution :
Variables must be initialized before use!
Do you think that when statement if (duplicateCheck) is executed, duplicateCheck is already assigned?
But you overlooked one point, enrolledCourses.size() may be equal to zero, in this case, the for loop will not be entered, and duplicateCheck will not be assigned