以下程序中的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
}
答案 0 :(得分:2)
代码
while ((line = bufferedReader.readLine()) != 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
}