-1

I have learnt about BufferedReader as well as BufferedWriter, so I decided to create a small text processor for the command line (meaning without interface, just in cmd/terminal). It asks a user for document name (Which will then create a file) and then user can type sentences. Each time user presses "enter" button, text is entered into the file and new line is created and then allowing user to type more. At the end, it will display a message saying file is created. NOW, I have encountered a problem where user would not be able to stop the process of entering data and creating file, because the program kept creating new lines despite entering nothing or quit keyword(which i stated in the code in order to quit the program.) Here is my original code:

import java.io.*;
class TextProcessor
{
public static void main(String[] args)
{
    try
    {
    System.out.println("Please enter name of the file");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //User input
    String file = in.readLine();
    BufferedWriter writer = new BufferedWriter(new FileWriter(file)); //Creating file as well as instance for inputting text to the file.


    System.out.println("Enter text");
    String line = "";

    do
    {
        line = ins.readLine();
        System.out.println(line);
        writer.write(line);
        System.out.println("Second " + line);
        writer.newLine();
    }
    while(line != "quit()");
    //while(line != null);


    in.close();
    writer.close();


    System.out.println("Text is created with entered text");
    }
    catch(IOException e)
    {
        System.out.println("Error occured");
    }
}

}

However, I found a solution to this, which is replacing do-while block with while one:

int counter = 0;
    while(counter != 1)
    {
        line = in.readLine();
        writer.write(line);
        if(line.equals("quit()"))
        {
            ++counter;
        }
        else {writer.newLine();}
    }

I have a question about this now, why can't I use do-while statement instead of while, even if it seems logical that the program would work? Thank you for reading this!!!!

P.S. I also wonder if I can bring small improvements to this or any other way creating this type of program. Thanks if you give feedback!

pavelexpertov
  • 19
  • 1
  • 2
  • 4

1 Answers1

0

Probably the error asked about the most.

Answer can be found here: How do I compare strings in Java?

while(line != "quit()");

must be

while(!line.equals("quit()"));
Community
  • 1
  • 1
jlordo
  • 37,490
  • 6
  • 58
  • 83
  • Why was this downvoted?? I mean this actually solves the issue. +1 from me though. – Rohit Jain Jul 20 '13 at 18:22
  • Thanx for +1, but I am surprised that I am 2 points down. Furthermore, this was a specific question and I had no idea that there was a difference between equals() and ==. Plus I wanted to find feedback for this code as well! – pavelexpertov Jul 20 '13 at 20:29