我目前正在开发一个程序,要求输入两个团队的名称和分数。当我请求输入第一队的姓名和 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();
}
}
最佳答案
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
关于Java Scanner 在 For 循环后不接受输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12821567/