The following code allows the user to enter a football team and a score. If the football team the user entered matches a team already in the arraylist, then it executes the code.
Why does the else statement still execute when the outer if-statement is true? (i.e. the itCounter still increments even though the if-statement is executed). How do I ensure that it is no longer executed after the 'If' is executed?
int homeScore = 0;
int awayScore = 0;
int itCounter = 0;
boolean again = true;
while (again) {
System.out.println("");
System.out.println("Enter name of Home team: ");
final String homeName = input.next();
Iterator<FootballClub> it = premierLeague.iterator();
while (it.hasNext()) {
if ((it.next().getClubName()).equals(homeName)) {
System.out.println("Enter number of goals scored by " + homeName + ":");
Scanner input2 = new Scanner(System.in);
homeScore = input2.nextInt();
premierLeague.get(itCounter).setGoalsScored(homeScore);
System.out.println("itCounter value = " + itCounter);
again = false;
} else {
itCounter++;
System.out.println("itCounter increased, value = " + itCounter);
}
if (itCounter == premierLeague.size()) {
System.out.println("You must enter a valid team!");
itCounter = 0;
System.out.println("itCounter increased, value = " + itCounter);
}
}
}
ifstatement are you referring to?if, because what you are asking doesn't make sense. You may think that both theifandelseparts are executing, but they are not. Maybe you are just observing 2 different iterations of thewhileloop.whileloop as-is is the same asfor (FootballClub club : premierLeague) { }, and it will iterate all the clubs, entering theelseclause for every club that is nothomeName. That's as-coded, whether that's as-intended is up to you to decide.