简体   繁体   中英

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. However, after the for loop, the scanner does not accept input for the name of the second team. 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.

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. So when the first loop ends, there is still one newline character left and your input.nextLine() returns a blank string. add a input.nextLine() after your loop to skip this blank line and to solve your problem like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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