Search code examples
javastringbuilder

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


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()
    }