我遇到以下代码问题:
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(); // get the char
} while (ch != 'q');
}
}
由于某种原因,System.out行重复3次。控制台的输出示例如下:
Press a key followed by enter: a
Press a key followed by enter: Press a key followed by enter: Press a key followed by enter:
我在Eclipse Kepler中尝试过这段代码并手动编译同样的问题。谷歌搜索答案已被证明是无用的。有什么想法吗?
添加了正确的代码
如果我输入的字符超过1个,我会得到4个System.out.println结果:
Press a key followed by enter: aa
Press a key followed by enter: Press a key followed by enter: Press a key followed by enter: Press a key followed by enter:
答案 0 :(得分:7)
所以你按a然后按回车键。然后,您将阅读这些字符
(这适用于Windows,例如在* nix系统上,换行符只是' \ n而不是\ r \ n)
你可以跳过例如所有的空白:
do {
System.out.print("Press a key followed by enter: ");
ch = (char) System.in.read();
while(Character.isWhitespace(ch)) {
ch = (char) System.in.read();
}
} while (ch != 'q');
答案 1 :(得分:2)
当您按Enter键时,它会在基于 windows 的系统(\ r \ n)中读取两个额外的字符。
如果您将代码更改为:
do {
System.out.print("Press a key followed by enter: ");
ch = (char) System.in.read(); // get the char
char ch1 = (char) System.in.read(); // carriage return
char ch2 = (char) System.in.read(); // line feed
} while (ch != 'q');
它将打印单个“按一个键,然后输入:”
如果您想要交叉验证,请打印ch1
和ch2
的int值,您将分别获得13
和10
。