示例:
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次提示呢?

解决方案 »

  1.   

    很简单,因为你输入x的时候要按一个回车,而回车也是两个字符,\r\n
    所以会输出两次不可见字符.
    测试代码如下: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("程序已经退出!");
    }
      

  2.   

    System.out.println("你输入的字符是:"+ch); 
    改成System.out.println("你输入的字符是:"+(int)ch); 
    就会发现输出结果有13和10,查了下ascii码表,
    13指回车,10指空格,因为你输入a,不等于x,所以又重新执行了while输出你输入"a"后按的回车键13,
    为什么输空格10不是很清楚
      

  3.   

    我试了下
    public static void main(String[] args)  throws Exception{
        char ch = ' '; 
    StringBuffer st= new StringBuffer();
    int i = 0;

    while(true){ 

     st.append((char)System.in.read()); 
         System.out.println("你输入的字符是:"+st.toString().replaceAll("\n", "<br>")); 
         System.out.println(i++);
         
    if(ch=='x') 
    break; 

      System.out.println("程序已经退出!"); 
        }  }
    a
    你输入的字符是:a
    0
    你输入的字符是:a1
    你输入的字符是:a
    <br>
    2
    b
    你输入的字符是:a
    <br>b
    3
    你输入的字符是:a
    <br>b4
    你输入的字符是:a
    <br>b
    <br>
    5
    他最后都多补了几个换行符 所以又多输出了几次
      

  4.   

    恩,原因就是当你输入a的时候,while还在继续执行,打印出a后会打印你敲的回车键!
    一个回车键也算两个字符。
    所以输入a的时候会执行3次System.out.pirntln();
    而输入x后,while不再执行。
    所以只执行后面的System.out.println("程序已经退出!");