[英]ELSE statement still executing even after IF is true
以下代碼允許用戶輸入足球隊和得分。 如果用戶輸入的足球隊與陣列列表中已有的球隊相匹配,則它將執行代碼。
當外部if語句為true時,為什么else語句仍然執行? (即,即使執行了if語句, itCounter
仍會增加)。 如何確保在執行“如果”后不再執行它?
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);
}
}
}
打破團隊的查找循環:
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!");
}
注意1:請務必重新開始循環,以重新設置所有變量的團隊。
注意2:請勿在同一輸入流上創建其他掃描儀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.