Issue
I am trying to understand why I cannot print my desired outcome. I have changed my loop logic around a few times but cannot see the issue.
I have an array list ArrayList<Landing> landings = new ArrayList<>();
I have the following method in the Landing
class to check the landing ID;
public boolean checkId(int id) {
if (this.landingId == id) {
return true;
} else {
return false;
}
}
I am trying to create some input handling where if the user inputs an ID which doesn't match an ID in the array list, an error message is printed. I can't seem to get the failed scenario to print the message
System.out.print("Please enter the landing ID: ");
int id = Integer.parseInt(sc.nextLine());
boolean unsuccessful = false;
for (int i = 0; i < landings.size(); i++) {
if (landings.get(i).checkId(id)) {
landings.get(i).printLandings();
unsuccessful = false;
break;
} else {
unsuccessful = true;
}
}
if (unsuccessful) {
System.out.println(
"\nThe ID you enterred does not match any landing");
}
break;
TIA
Solution
If you want to check if there's "any" (= at least one) match, you gotta start with boolean unsuccessful = true
.
Let's look at the simplest case: When the List
is empty, the loop won't run a single time. Though unsuccessful
will not be changed and has to set to true
before the loop.
Here's a simplified version.
boolean unsuccessful = true
for(...) {
if(matchFound) {
unsuccessful = false;
break;
}
}
if(unsuccessful) { print(...); }
Maybe you should also consider renaming the variable to success
(at least for me that's easier to read):
boolean success = false;
for(...) {
if(matchFound) {
success = true;
break;
}
}
if(!success) { print(...); }
As you can see, you also don't need the else
part anymore.
Answered By - Benjamin M
Answer Checked By - Candace Johnson (JavaFixing Volunteer)