使用System.in.read()时打印附加行

时间:2016-01-06 04:01:58

标签: java

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

        char ch;

        do {
            System.out.print("Press a key followed by ENTER: ");
            ch = (char) System.in.read();
        } while (ch != 'S');
    }
}

尝试学习java。这是一个简单的功能,但我得到的结果是

Press a key followed by ENTER: D
Press a key followed by ENTER: Press a key followed by ENTER: G
Press a key followed by ENTER: Press a key followed by ENTER: E
Press a key followed by ENTER: Press a key followed by ENTER: F
Press a key followed by ENTER: Press a key followed by ENTER: S

系统将在Intellij中打印“按一个键然后按Enter:”两次,在eclipse中将打印三次。

请帮忙!

1 个答案:

答案 0 :(得分:0)

因为你正在从控制台读取字符。每个“ENTER”=='\ n'都将被视为一个角色。所以你的         (char)System.in.read() 对于它读取的每个字符,取2个字符和循环会增加。对于“ENTER”。