[英]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? 当外部if语句为true时,为什么else语句仍然执行? (ie the
itCounter
still increments even though the if-statement is executed). (即,即使执行了if语句,
itCounter
仍会增加)。 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. 注意1:请务必重新开始循环,以重新设置所有变量的团队。
Note 2: Don't create another Scanner on the same input stream. 注意2:请勿在同一输入流上创建其他扫描仪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.