简体   繁体   English

Java扫描程序在For循环后不接受输入

[英]Java Scanner not accepting input after the For loop

I am currently working on a program that requests input for the names and scores of two teams. 我目前正在开发一个程序,要求输入两个团队的名称和分数。 When I request input for the name and 9 scores of the first team, the scanner accepts input just fine. 当我要求输入一队的名称和9分时,扫描程序会接受输入。 However, after the for loop, the scanner does not accept input for the name of the second team. 但是,在for循环之后,扫描程序将不接受第二组名称的输入。 This is not the entire program, but I have included all the code up until the point where it is giving me trouble. 这不是整个程序,但是我已经包括了所有代码,直到给我造成麻烦为止。 I suspect that it may have something to do with the for loop because team2 accepts user input just fine when I place it before the for loop. 我怀疑它可能与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's nextInt method does not skip a line, only fetches the int. 扫描仪的nextInt方法不跳过一行,仅获取int。 So when the first loop ends, there is still one newline character left and your input.nextLine() returns a blank string. 因此,当第一个循环结束时,仍然剩下一个换行符,而您的input.nextLine()返回一个空字符串。 add a input.nextLine() after your loop to skip this blank line and to solve your problem like this: 在循环后添加一个input.nextLine(),以跳过此空行并解决如下问题:

for(int i = 0; i < team1Scores.length; i++){
    team1Scores[i] = input.nextInt();
    team1Total += team1Scores[i];
    }
input.nextLine();
//rest of your code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM