1

I'm writing a program that asks how many users are going to use it, based off that response it creates an array of String type holding the names of each user. The problem I'm running into is that when I execute the for-loop that stores each name into the String type array, it prints out the statement twice before accepting a string input. Anyone know what I'm doing wrong?

    Scanner input = new Scanner(System.in);
    
    System.out.print("Please enter the number of users: ");
    int numUser = input.nextInt();
    
    String[] userArray = new String[numUser];
    
   
    for (int i = 0; i < numUser; i++) {
        System.out.print("For user " + (i+1) + ", please type your username followed by enter: ");
        String inputUsername = input.nextLine(); 
        userArray[i] = inputUsername;
    }
    for (int i = 0; i < numUser; i++) {
        System.out.println(userArray[i]);
    }
}

OUTPUT

notice in the image of my output that my statement is outputted twice on the same line and on the second statement I can finally start inputting names storing them into the array. Also, I have a for-loop that displays the names, notice that the first name is blank and after that it displays the rest of the names. Image of the output of my Java program after it's been ran

pewpewpew
  • 11
  • 1
  • 1
    After this line: `int numUser = input.nextInt();` you have to add a call to `nextLine()` to remove the newline that wasn't read by `nextInt()`. – markspace Oct 13 '21 at 20:02

1 Answers1

2

Insert input.nextLine() before for loop.

Because nextInt () doesn't read the whole line but only an int number. The next nextLine () consumes the line and therefore everything after the number. You can try to insert "3 User1" in the input line in the number of users and see that it takes you as input first 3 as the number of users and then User1 as the user.

Test Image

user192837
  • 78
  • 5
  • I edit comment. Use input.nextLine() before for loop. – user192837 Oct 13 '21 at 20:08
  • I'm trying to figure this out having little experience with the Java console scanner. Do you know how the input scanner and System.out interact here? I understand that the first "input.nextInt();" would set the scanner to the end of the line, and that the first nextLine fails because all nextLine reads between the int input and the first entered name would be a newline character and nothing else. But I would have expected the first print to appear in the line with the initial int input too. For the second one to appear in the same line there has to be some weirdness. – Shrimperator Oct 13 '21 at 20:24