1

我目前正在开发一个程序,该程序要求输入两个团队的名称和分数。当我要求输入第一队的姓名和 9 分时,扫描仪接受输入就好了。但是,在 for 循环之后,扫描器不接受输入第二个团队的名称。这不是整个程序,但我已经包含了所有代码,直到它给我带来麻烦为止。我怀疑它可能与 for 循环有关,因为当我将它放在 for 循环之前时,team2 可以很好地接受用户输入。

import java.util.Scanner;
public class sportsGame{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        String team1;
        String team2;
        int team1Scores[] = new int[9]
        int team1Total = 0;
        int team2Scores[] = new int[9];
        int team2Total = 0;

        System.out.print("Pick a name for the first team: ");
        team1 = input.nextLine();

        System.out.print("Enter a score for each of the 9 innings for the "
                + team1 + " separated by spaces: ");
        for(int i = 0; i < team1Scores.length; i++){
            team1Scores[i] = input.nextInt();
            team1Total += team1Scores[i];
        }
        System.out.print("Pick a name for the second team: ");
        team2 = input.nextLine();
    }
}
4

1 回答 1

5

Scanner 的 nextInt 方法不会跳过一行,只获取 int。因此,当第一个循环结束时,还剩下一个换行符,并且您的 input.nextLine() 返回一个空白字符串。在循环之后添加一个 input.nextLine() 以跳过此空白行并解决您的问题,如下所示:

for(int i = 0; i < team1Scores.length; i++){
    team1Scores[i] = input.nextInt();
    team1Total += team1Scores[i];
    }
input.nextLine();
//rest of your code
于 2012-10-10T14:19:30.613 回答