Skip to content
Advertisement

Writing multiple lines using PrintWriter in Java

I am sorry if this question is already answered on the internet but by looking at the ‘similar questions’ I couldn’t find an answer for my problem. So basically I’m trying to understand why using PrintWriter to write lines of text into a file apparently skips the first line every 2 lines I give.

This is the method I use in its own class:

JavaScript

When I call it from main with:

JavaScript

and write:

JavaScript

The output text is actually:

JavaScript

I am sure the problem is the while loop, because if I input the lines manually one by one it works correctly, but I don’t understand exactly why it behaves like it does right now.

Advertisement

Answer

JavaScript

You repeat your user.nextLine(); within your loop, so line is not the same as the one you compare to “stop”.

Rewrite that part as:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement