我目前正在制作一个程序,要求输入两个团队的名称和分数。当我请求输入名称和第一组的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();
}
}
答案 0 :(得分: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