繁体   English   中英

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

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

我目前正在开发一个程序,要求输入两个团队的名称和分数。 当我要求输入一队的名称和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();
    }
}

扫描仪的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

暂无
暂无

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

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