【发布时间】:2014-06-09 06:52:08
【问题描述】:
我目前正在创建一个 java 程序,它应该再次读取控制台并将其打印出来。代码如下所示:
import java.io.IOException;
public class printer {
public static void main(String[] args){
int i;
try {
while ((i = System.in.read()) != -1) {
char c = (char)i;
System.out.print(c);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
问题是,如果您在控制台中键入以下文本,您将打印第一行,但由于它在“打印”一词之后是 "\n",因此程序不会在没有我按 Enter 的情况下打印第二行手动
This is the text I want to print
And now I pressed Enter
当我按下回车键时,得到第二行,结果是:
This is the text I want to print
And now I pressed Enter
这不是它通常的样子。
如果第一行没有自动打印,我会更喜欢。我想按 Enter 并同时获取两条线。可以像我一样使用while ((i = System.in.read()) != -1)吗?
【问题讨论】:
-
是的,控制台文本在“print”之后有一个“/n”,这使得我的程序可以打印直到该字符的所有内容。
-
让我改写一下。 "\n" 是换行符。 “/n”是一个正斜杠,后跟一个“n”,没有任何特殊含义。
-
抱歉,我不知道,我的意思是“\n”:)