0

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.

Edson
  • 255
  • 1
  • 3
  • 18
  • Please post full code. – Sasikumar Murugesan Nov 08 '18 at 19:42
  • 2
    Er isn't that just the text you typed yourself, followed by the output of the code? – OpenSauce Nov 08 '18 at 19:43
  • @OpenSauce - huh? I manually posted the output. The code i'm using for a practice problem on a website that runs the code I input. It shows me the output I posted above. – Edson Nov 08 '18 at 21:05
  • @Edson the Scanner gets its input from somewhere, presumably from you typing it into the console. Since you type into the console, what you type appears in the console. The confusion probably comes from you putting the code into a website which makes it look like your input is separate from the console content. If you just ran the code as a standalone Java application it would be more clear. – OpenSauce Nov 08 '18 at 21:14
  • @OpenSauce - Yup, I understand what you asked now, I edited my post with an explanation. – Edson Nov 08 '18 at 21:17

2 Answers2

1

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.

Mark
  • 5,089
  • 2
  • 20
  • 31
1

This will give you the expected output:

System.out.println("name #" + i + "?" + " ");
console.nextLine();
Justin
  • 1,356
  • 2
  • 9
  • 16
  • Thanks, it worked after I used "print" instead of "println". Any ideas as to why the original code wasn't working correctly? – Edson Nov 08 '18 at 21:11
  • When constructing the string to print out, java attempts to get the input before printing out to console. The function must finish before the line prints out – Justin Nov 08 '18 at 22:16