从java控制台程序的命令行中读取段落

时间:2013-05-13 10:04:54

标签: java console readline eof paragraph

以下程序中的while循环不会终止,因此我无法在尝试将变量段打印到控制台的最后一行中获取输出。有类似的问题,但解决方案并不实际,我不能这样做。请提出解决方案。

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

}

1 个答案:

答案 0 :(得分:2)

代码

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

如果你没有为行分配null,并且你不能通过控制台为对象分配null,那么

永远不会成立,这意味着你必须为某些东西编写代码,比如输入键或任何其他字符来结束输入。 / p>

喜欢

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

这意味着当您在结束时键入exit时,程序将终止并打印段落。

您可以尝试使用此代码段

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

    }