Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my scanner skipping every other user input when I print my StringBuilder?

public static void main(String[] args) {
    String welcomeMsg = "Enter inputs. Leave blank and hit Enter when done."

    Scanner sc = new Scanner(System.in);
    System.out.println(welcomeMsg);

    StringBuilder attendees = new StringBuilder();

    while (!sc.nextLine().equals("")){
        attendees.append(sc.nextLine());
    }
    System.out.println(attendees);
}

The scanner seems to be working fine. I can input say, a then hit enter. Hit b and hit enter. And so on through h. Then, leaving the line blank and hitting enter, it gets to work.
But the output is:

bdfh

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This happens because you read the line twice, once here while (!sc.nextLine().equals("")) then again here attendees.append(sc.nextLine()); which causes the first line read each loop cycle to be skipped.

To fix this simply read once using a temporary string. Here is one option:

//Read to temporary string
String line = sc.nextLine();

//Now process the string
while (!line.equals("")){
    attendees.append(line );

    //read the next line for the next loop cycle
    line = sc.nextLine()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading