0

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:

public class IO_Utilities {

public static void Write(String outputName){

    PrintWriter outputStream = null;
    try {
        outputStream = new PrintWriter(outputName);
    } catch (FileNotFoundException e) {
        System.out.println(e.toString());
        System.exit(0);
    }
    System.out.println("Write your text:");
    Scanner user = new Scanner(System.in);
    while(!user.nextLine().equals("stop")) {
        String line = user.nextLine();
        outputStream.println(line);
    }
    outputStream.close();
    user.close();
    System.out.println("File has been written.");
}

When I call it from main with:

IO_Utilities.Write("output.txt");

and write:

first line
second line
third line
stop
stop

The output text is actually:

second line
stop

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.

1
  • it's because you repeat this: user.nextLine(); in your loop Commented Feb 8, 2021 at 9:34

1 Answer 1

1
while(!user.nextLine().equals("stop")) {
        String line = user.nextLine();
        outputStream.println(line);
    }

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:

String line = user.nextLine();
while( !line.equals("stop")) {
  outputStream.println(line);
  line = user.nextLine();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I just came back to answer my own stupid question but yes that was the problem, I needded to initialize the string variable outside to compare it with the stop case, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.