【问题标题】:Java. System.in.read() and "\n" in console [duplicate]爪哇。控制台中的 System.in.read() 和“\n”[重复]
【发布时间】: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”:)

标签: java system.in


【解决方案1】:

如果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

【讨论】:

  • 您应该在此处使用 '\n' 而不是 String 文字,因为此处要与 String 进行比较 c 将自动装箱为 Character 并且在任何情况下比较都会失败。
  • 抱歉,您当然应该将 char 与 char 进行比较,已编辑。好地方;)
  • 问题不在于它打印了一个新行。问题是它会自动打印第一部分(第一行),然后我必须按 Enter 才能获得第二行。我希望按一次 Enter 并获取所有内容。
  • 已编辑,希望能回答您的问题!
  • 有什么方法可以做到这一点,而无需在“.”处退出循环。我想在按 Enter 时结束循环
猜你喜欢
  • 2020-08-03
  • 2016-04-20
  • 2014-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-07
  • 2012-11-11
相关资源
最近更新 更多