Search code examples
javaarraysfor-loopskip

for loop skip issue


I have this code, and everything is running as i want to except the face that it skips the first time it is supposed to wait for the next input by the user. Here is the code:

import java.util.Scanner;
public class mainThread {
    public static int size;
    public static int counter;
    public static Scanner input = new Scanner(System.in);
    public static String currentIn;
    public static void main(String[] args){
        System.out.println("Please type the desired amount of players: ");
        size = input.nextInt();
        String nameArray[] = new String[size];
        for(int counter = 0; counter < size; counter++){
            System.out.println("Please enter the name of player " + (counter+1));
            currentIn = input.nextLine();
            nameArray[counter] = currentIn;
            System.out.println(nameArray[counter]);
        }
    }
}

Here is what the console says:

Please type the desired amount of players: 
3
Please enter the name of player 1

Please enter the name of player 2
Jacob
Jacob
Please enter the name of player 3

It completely skips the first loop, and i can't seem to figure out why. Thanks for your time!


Solution

  • I'm not sure what the problem is, but if you replace the line

    currentIn = input.nextLine();
    

    With:

    currentIn = input.next();
    

    It will work.