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

困扰了好久的问题 str = (char) System.in.read()嵌套在while中
import   java.util.*;
import   java.io.*;
public   class   Circle{

public   static   void   main(String   args[]){
    int   i=0;
    int   j=0;
    char   str= '   ';
    while   (j <=1){
                    i=0;
    while(true){
     
System.out.println( "enter   a   char ");
try{str   =   (char)   System.in.read();
                    System.out.println(i);
    System.out.println(str);
    if(i==3)   break;
    i++;
      }catch(IOException   e){}
 
    }
    j++;
    }
}
}  

运行结果:
enter   a   char
a
0
a
enter   a   char
1                               //为什么i=1   时不能输入字符呢

enter   a   char
2                             //为什么i=2   时不能输入字符呢   很迷茫   !!!


enter   a   char
  光标

------解决方案--------------------
str = (char) System.in.read();
第一次接受到你的输入后,
第2次执行的时候不会等待你的输入,默认将str置为str= " ";
所以第一次输入的时候输入串就行了,你输入“abcdefg”试试就明白了
------解决方案--------------------
在 str = (char) System.in.read(); 后面加上一行

System.in.skip(2);

就可以了,因为里面缓存着回车(回车也是字符哦)的关系。