【发布时间】:2014-06-09 14:50:47
【问题描述】:
我正在尝试打印与用户粘贴到控制台相同的字符串。 我的代码如下所示:
import java.util.Scanner;
public class reader {
public static void main(String[ ] args)
{
Scanner scan = new Scanner( System.in );
StringBuffer buf = new StringBuffer();
while ( scan.hasNextLine() ) {
buf.append( scan.nextLine() );
buf.append( "\n" );
}
String s = buf.toString();
System.out.print(s);
}
}
问题(我认为)是循环是无限的,即使用户只在控制台中粘贴 4 行,它也不会破坏 while 循环。
我想要的是“System.out.print(s);”打印 s。我该怎么办?当用户按 Enter 时,我可以中断循环吗?
【问题讨论】:
-
您需要定义一个端点。您想要什么时候打破循环?
标签: java loops while-loop java.util.scanner