简体   繁体   中英

ELSE statement still executing even after IF is true

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? (ie 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);
        }
    }
}

Break out of the lookup-loop for the team:

boolean found = false;
Iterator<FootballClub> it = premierLeague.iterator();
int itCounter = 0;
while (it.hasNext()) {
    if ((it.next().getClubName()).equals(homeName)) {
        System.out.println("Enter number of goals scored by " + homeName + ":");
        // Scanner input = new Scanner(System.in);
        homeScore = input.nextInt();
        premierLeague.get(itCounter++).setGoalsScored(homeScore);
        again = false;
        found = true;
        break;
    }
}
if( ! found ){
    System.out.println("You must enter a valid team!");
}

Note 1: Take care to restart the loop searching for the team with all variables properly reset.

Note 2: Don't create another Scanner on the same input stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM