首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

这个输入流System.in.read()读入字符为什么会产生这样的效果?该如何处理

2012-03-19 
这个输入流System.in.read()读入字符为什么会产生这样的效果?示例:public class TestWhile {public static

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

热点排行