Search code examples
javafor-loopstringbuilder

StringBuilder append in for loop in Java


When I execute the following:

static void Append() {
    StringBuilder sb = new StringBuilder();
    System.out.print("How many words do you want to append? ");
    int n = input.nextInt();
    System.out.println("Please type the words you want to append: ");
    for (int c = 1; c <= n; c++) {
        String str = input.nextLine();
        sb.append(str);
        System.out.print(" ");
    }
    System.out.print(sb);

}

Let's say if I put 3, then the computer lets me type only 2 words..

This is the output:

How many words do you want to append? 3
Please type the words you want to append: 
 I
 am
 Iam

Also, why is there a space before the words? the print function is after the input function. So shouldn't it be the opposite?


Solution

  • If you debug that program, you can find that the first time of loop will get input.nextLine() with an empty string. This is when the problem occurs.

    When you input a 3 and a \n for int n = input.nextInt();, the input buffer contains "3\n", and input.nextInt(); will just take that "3", like the image below:

    the position is 1 where the position of input is 1, remaining the "\n" in the buffer. Then when the program required for nextLine(), it will read the buffer until a "\n", which results in reading an empty string.

    the position changed to 2 after a nextLine()

    So a possible workaround is to add a String empty = input.nextLine(); before the loop, or use input.next(); instead of input.nextLine();, since in the document says, input.next(); will return the next token.

    Update: Notice that no one answers your second question in the bottom...

    You should modify the line System.out.println(" "); in the loop into sb.append(" ");.