System.in.read()行为我无法解释 [英] System.in.read() behaviour i can't explain

查看:185
本文介绍了System.in.read()行为我无法解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class E92StringDemo {

 public static void main(String args[]) throws java.io.IOException {

      String strObj1 = "First String";

      for(int i=0;i<strObj1.length();i++) {

        System.out.print(strObj1.charAt(i));
        System.in.read(); //just to pause the execution till i press enter key

      }
   }
}

我希望输出结果如下:

F
i
r
s
t...

但输出结果如下: / p>

but the output is coming like:

F
ir
st
S
tr
in
g

我不确定为什么每按一次就会在一行中显示2个字符一个输入键(\ n)?

I am not sure how come 2 characters are getting displayed in one line with every press of an enter key(\n)?

我正在运行 Windows 8 并使用命令提示符使用 javac 。

I am running windows 8 and using a command prompt to run the file using javac.

推荐答案

Windows上的ENTER生成2个字符(CRLF),而read()仅消耗其中1个字符。
您必须为所需行为消耗2个字符。只需添加另一个 System.in.read(),您就会看到。

下面介绍按ENTER时字符的生成和消耗。 13代表CR,10代表LF。

F
13i10r
13s10t
13 10S
13t10r
13i10n
13g10

ENTER on Windows generates 2 characters (CRLF) whereas read() only consumes 1 of them. You must consume 2 characters for the desired behaviour. Just add another System.in.read() and you will see.

The following explains the generation and consumption of characters when you press ENTER. 13 represents CR and 10 represents LF. F 13i10r 13s10t 13 10S 13t10r 13i10n 13g10

这篇关于System.in.read()行为我无法解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆