Java - if语句保持循环

时间:2015-03-18 21:44:11

标签: java if-statement

我在使用if语句时遇到了一些问题。场景是,如果用户想要英国队,则应该输入1,如果他们想要美国队,则输入2。一旦他们选择一个区域,就会出现一个团队列表,他们输入团队的数量,该团队的信息应该打印出来,但由于某种原因,它只是不断循环并要求进入一个团队。我在这里稍微简化了我的代码,否则它会太大了。

ArrayList<STeam> teams = rCSV.readSTeams("sports-teams.csv");
Scanner UInput = new Scanner(System.in);
System.out.println("Enter 1 for British teams or 2 for American teams");
int choice = UInput.nextInt();
for (STeams st1 : teams) {

    if (choice == 1) {
        System.out.println("Choose: 1. London FC");
        int choice2 = UInput.nextInt();
        {
            if (choice2 == 1) {
                if (st1.getName().equals("London FC")) {
                    System.out.println(st1);
                }
            }
        }
    }
    else if (choice == 2) {
        System.out.println("test");
    }
}

如果这非常混乱,请道歉。 我有一个单独的类读取文件和一个单独的类为体育团队,我知道这些工作,因为我做了类似的事情,但只使用1 if语句在另一个而不是2。

3 个答案:

答案 0 :(得分:0)

choice永远不会在for循环中更新。

您可能想要这样做:

for (STeams st1 : teams) {
    int choice = UInput.nextInt();
    if(choice == 1) {
    // ...
}

答案 1 :(得分:0)

您正在使用此for (STeams st1: teams),这可能是遗留代码。因为它没有括号,所以for将不断循环。


编辑:好的,你可能想要这样的东西:

ArrayList britishTeams = rCSV.readSTeams(“sports-teams.csv”);         扫描仪UInput =新扫描仪(System.in);

    System.out.println("Enter 1 for British teams or 2 for American teams");
    int choice = UInput.nextInt();

    if (choice == 1) 
    {
        for(int option = 0; option<britishTeams.size; option++)
            System.out.println("Option " + option + ": " + britishTeams.get(option).name);    
        int choice2 = UInput.nextInt();
        System.out.println("You chose: " + britishTeams.get(choice2).name);   
    }

要添加美国团队,请不要再重复/粘贴此内容,制作代表团队列表并选择一种方法的代码; - )

答案 2 :(得分:0)

嘿,看起来你在没有任何条件的情况下运行循环。所以它会一直运行直到你的团队中有令牌。完成选择后,您需要使用break。

相关问题