即使IF为真,ELSE语句仍然执行

时间:2015-11-14 19:14:43

标签: java arrays

以下代码允许用户输入足球队和分数。如果用户输入的橄榄球队与已经在arraylist中的团队匹配,则它执行代码。

为什么当外部if语句为真时,else语句仍然执行?(即即使执行了if语句,itCounter仍然递增)。我如何确保在' If'之后不再执行该操作。被执行了吗?

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);
        }
    }
}

1 个答案:

答案 0 :(得分:5)

突破团队的查找循环:

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:不要在同一输入流上创建另一个扫描仪。