读书人

困扰了好久的有关问题 str = (char) S

发布时间: 2011-11-30 21:16:57 作者: rapoo

困扰了好久的问题 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);

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

读书人网 >J2SE开发

热点推荐