读书人

这个输入流System.in.read()读入字符为

发布时间: 2012-03-19 22:03:05 作者: rapoo

这个输入流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("程序已经退出!");    } 

读书人网 >J2SE开发

热点推荐