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
x
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:
JavaScript
IO_Utilities.Write("output.txt");
and write:
JavaScript
first line
second line
third line
stop
stop
The output text is actually:
JavaScript
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.
Advertisement
Answer
JavaScript
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:
JavaScript
String line = user.nextLine();
while( !line.equals("stop")) {
outputStream.println(line);
line = user.nextLine();
}