Search code examples
javajava.util.scanneruser-inputsystem.outconsole-input

Input line from Scanner object gets printed before official print command


I have a the following method below that receives a Scanner object with N number of lines, each with a a one word string.

    public static void longestName(Scanner console, int n) {

        for (int i = 1; i <= n; i++) {

          System.out.println("name #" + i + "?" + " " + console.nextLine());

        }

    }

Instead of this (expected output)...

name #1? roy
name #2? DANE
name #3? Erik
name #4? sTeFaNiE
name #5? LaurA

...I'm getting this

roy
name #1? roy
DANE
name #2? DANE
Erik
name #3? Erik
sTeFaNiE
name #4? sTeFaNiE
LaurA
name #5? LaurA

Why is the "nextLine()" from the Scanner object being printed once prior to the actual print command output?

****** This is a practice problem I'm using and they only ask me to define a method "longestName" that takes a Scanner object and an integer "n" denoting the number of names in the Scanner object.

The output above is a result of the method being used with a Scanner object with "n" number of names.


Solution

  • This will give you the expected output:

    System.out.println("name #" + i + "?" + " ");
    console.nextLine();