我正在创建一个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)
?
答案 0 :(得分:0)
如果c不等于换行符,请将其打印出来?
if(c != '\n'){
System.out.println(c);
}
修改
在下面的示例中,我使用句号终止输入。'。在循环中,将所有输入存储在String中直到它终止,然后打印现在包含两行的String。
import java.io.IOException;
public class Main {
public static void main(String[] args){
int i;
String line = "";
try {
while ((i = System.in.read()) != '.') {
char c = (char)i;
line = line + c;
}
System.out.println(line);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
我的控制台看起来像这样。前两行是输入,后两行是输出。
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