在我的输入被要求之前,Java For循环正在循环

时间:2016-01-02 12:34:00

标签: java loops for-loop

当我运行我的程序时,我的for循环输出“输入游戏分数?”这一行。在我有时输入之前两次,在构造它时犯了一个愚蠢的错误。

import java.util.Scanner;

public class Project {

public static void main (String[] args){

Scanner scan = new Scanner(System.in);
System.out.println("What is your name?");   
    String playername = scan.nextLine();


    System.out.println("How many games will you be entering?"); 
    int numofgames = scan.nextInt();

    /* Creating the arrays*/
    String[] game = new String[numofgames];
    int[] scores = new int [numofgames];
    int[] mins = new int [numofgames];

    /* Creating a temp array to store the game data before splitting*/
    String[] temparray = new String[numofgames];

    /*Getting the users game data and storing it into the temp array*/
    for (int count=1; count <= numofgames; count++){
        System.out.println("Enter a game score?(Game name:Scores:Mins)");
                temparray[count] = scan.nextLine();


    }}}

1 个答案:

答案 0 :(得分:0)

点击“输入”后,功能scan.nextInt()不会丢弃换行符。所以它保留在缓冲区中,并在调用scan.nextLine()时读取。只需在scan.nextInt()

之后清空缓冲区
int numofgames = scan.nextInt();
scan.nextLine(); // remove newline from buffer

您还应该修复循环边界:

for (int count=0; count < numofgames; count++) {
...
}