Input line from Scanner object gets printed before official print command

1.2k views Asked by At

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.

2

There are 2 answers

2
Justin On BEST ANSWER

This will give you the expected output:

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

It is not printing it multiple times, it is the text you have typed into the console yourself. You type Erik as you can see, only after that it will process your print statement and print name #3? Erik where Erik is the text you've typed in.