-1

我目前正在创建一个 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)像我一样使用吗?

4

1 回答 1

0

如果 c 不等于换行符,打印出来?

if(c != '\n'){
    System.out.println(c);
}

编辑

在下面的示例中,我以句号“.”终止输入。在循环中,将所有输入存储在一个字符串中,直到它终止,然后打印现在包含两行的字符串。

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
于 2014-06-09T07:09:38.187 回答