日期:2014-05-20  浏览次数:20678 次

这个输入流System.in.read()读入字符为什么会产生这样的效果?
示例:
public class TestWhile {
  public static void main(String[] args) throws Exception{
char ch=' ';
while(true){
ch=(char)System.in.read();
System.out.println("你输入的字符是:"+ch);
if(ch=='x')
break;
}
  System.out.println("程序已经退出!");
  }
}
//*********运行结果
a
你输入的字符是:a
你输入的字符是:
你输入的字符是:

x
你输入的字符是:x
程序已经退出!
Press any key to continue...
//**********
为什么输入a的时候,连续出现3次提示呢?

------解决方案--------------------
很简单,因为你输入x的时候要按一个回车,而回车也是两个字符,\r\n
所以会输出两次不可见字符.
测试代码如下:
Java code

public static void main(String[] args) throws Exception {
        char ch = ' ';
        while (true) {
            ch = (char) System.in.read();
            if (ch == '\r') {
                System.out.println("输出/r");
            } else if (ch == '\n') {
                System.out.println("输出/n");
            } else {
                System.out.println("你输入的字符是:" + ch);
            }
            if (ch == 'x')
                break;
        }
        System.out.println("程序已经退出!");
    }