【问题标题】:System.in.read() - why two empty lines after Carriage Return?System.in.read() - 为什么回车后有两个空行?
【发布时间】:2017-02-24 10:29:32
【问题描述】:

我搜索了很多,但没有找到准确的答案。

为什么我的程序在读出我的回车后会多出一行(所以是两个空行)?

当我在carriageReturn (13) 之前完成while 循环时,它会在“c”之后直接打印“------”。

这是我的程序:

import java.io.*;
class IOIntro {
public static void main(String args[]) throws IOException {
     int letter = 0;
    System.out.print("Type a letter and press Enter: ");

   while((letter = System.in.read ()) !=10) { //loops throw whole inputStream until there is a new Line Feed
       System.out.println("You typed: " + letter);
       System.out.println((char) letter);
    }
   System.out.print("--------");
   }
 }

13(回车)之后,10(换行)之前的输出:

Type a letter and press Enter: ads
You typed: 97
a
You typed: 100
d
You typed: 115
s
You typed: 13


--------

13 前的输出(回车):

Type a letter and press Enter: ads
You typed: 97
a
You typed: 100
d
You typed: 115
s
--------

感谢您的帮助。

【问题讨论】:

  • 因为您正在打印换行符,所以 println 以换行符结束该行。
  • 谢谢!明白了!
  • 请注意,这只发生在 Windows 或其他使用 \r\n 作为换行符分隔符的平台上。检查this demo,它演示了\n- 和\r\n-style 换行符。

标签: java inputstream


【解决方案1】:

观察这一行:

System.out.println((char) letter);

您正在打印带有 ASCII 码 13 的字母,它代表“回车”。另外,您正在使用println,它会在其输入的末尾打印一个额外的新行。所以控制台会打印两个空行。

更新:

Enter 键又名Return 键将\r 或字符代码13 发送到控制台。因此,在您的 while 循环条件中,进行以下更改:

while((letter = System.in.read ()) != '\r') { 

希望这会有所帮助!

【讨论】:

  • 13 是回车。 10 是新行。
  • 已更正。谢谢!
  • 为什么打印回车会打印换行符呢?它们不是一回事。
  • 我认为控制台不能回到同一行的开头。它返回到行首的唯一方法是转到下一行。
  • 谢谢!这有帮助。所以我对“Curriage Return”的理解是不对的;)
【解决方案2】:

13 是回车,println() 写入换行符。

所以:

 System.out.println("You typed: " + letter);
 System.out.println((char) letter);

对于“a”,打印:

 Your typed: 100{newline}a{newline}

对于“{newline}”,打印:

 You typed: 13{newline}{cr}{newline}

...这就是你所看到的。

【讨论】:

    【解决方案3】:

    当您按 Enter 时,在 Windows 上您会返回两个字符:回车 (13) 和换行 (10)。

    代码 13 有点令人困惑,因为在某些平台(例如 OSX)上它意味着 新行

    您的 IDE 可能正在尝试安全运行,并将其解释为换行符。如果您使用的是 Eclipse,请参阅bug 76936

    \r (13) 应该将光标移动到行首,但停留在该行

    如果您在真正的控制台中运行应用程序,您应该只会看到一个换行符。

    >java -cp . IOIntro
    Type a letter and press Enter:
    You typed: 13
    
    --------
    >
    

    如果您想在 Enter 时静默退出,请将您的测试从 10 更改为 13

       while((letter = System.in.read ()) !=13) {
           System.out.println("You typed: " + letter);
           System.out.println((char) letter);
        }
    

    【讨论】:

    • 13 是回车。 10 是新行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2012-04-19
    • 1970-01-01
    • 2020-07-24
    相关资源
    最近更新 更多