Search code examples
javaconsolereadlineeofparagraph

Reading a paragraph from the command line on java console program


The while loop in the following program does not terminate so I can't get the output in the last line that tries to print the variable paragraph to console. There are similar problems but the solutions are not practicle and I could not do them. Please suggest a solution.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {


    public static void main(String[] args) throws IOException {
        String line = "";
        String paragraph = "";

        System.out.println("Enter the text: ");
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(isr);
             while ((line = bufferedReader.readLine()) != null)
             {
                  paragraph = paragraph + line + " ";
             }
          isr.close();
          bufferedReader.close();
          System.out.println(paragraph);
    }//method main ends here

}

Solution

  • The code

    while ((line = bufferedReader.readLine()) != null)

    will never be true if you dont assign null to line , and you cant assign null to an object through console , so that means you have to code it for something , like enter key or any other character to end the input.

    like

    while(!(line.equals("exit")))
    {
          //whatever
    }
    

    This means when you type exit at end , the program will terminate and print the paragraph.

    You can try this snippet

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
        public class Test {
    
    
            public static void main(String[] args) throws IOException {
                String line = "";
                String paragraph = "";
    
                System.out.println("Enter the text: ");
                InputStreamReader isr = new InputStreamReader(System.in);
                BufferedReader bufferedReader = new BufferedReader(isr);
                     do
                     {
                         line = bufferedReader.readLine();
                          paragraph = paragraph + line + " ";
                     }while(!line.equals("exit"));
                  isr.close();
                  bufferedReader.close();
                  System.out.println(paragraph);
            }//method main ends here
    
        }