请问:
为什么我的第二次输入被跳过了呢??
程序如下:public class Game
{
int number;
char str;
void count()
{
System.out.println("\t Welcome to this Foolish Game!!\n\t\tGood luck to you\n\n\n\tYou(Y) first or Computer(N) ?");
try{
str = (char)System.in.read();
if(str=='Y')
{
str = (char)System.in.read();
}
}catch(Exception a){System.out.println(a);}
}
public static void main(String[] a)
{
Game g = new Game();
g.count();
}
}
为什么我的第二次输入被跳过了呢??
程序如下:public class Game
{
int number;
char str;
void count()
{
System.out.println("\t Welcome to this Foolish Game!!\n\t\tGood luck to you\n\n\n\tYou(Y) first or Computer(N) ?");
try{
str = (char)System.in.read();
if(str=='Y')
{
str = (char)System.in.read();
}
}catch(Exception a){System.out.println(a);}
}
public static void main(String[] a)
{
Game g = new Game();
g.count();
}
}
打出Welcome信息后,输入“Y”敲回车。这时System.in里的信息是:'Y','\r','\n'
执行一次System.in.read()读一个字节。
所以读了'Y'后,因为还有内容可读,不需要等用户再输入,直接读了'\r'。然后程序就执行终了了。
如果你输出的是‘Yk',若你把最后的str打印出来,就会看到输出了k。
解决办法就是读两次,在输入一次以后每次读入时:用System.in.read()读入一个"\r"
那么再System.in.read()读就能读入正确字符。
{
System.out.println("Welcome to this Foolish Game!!");
System.out.print("Good luck to you ! You(Y) first or Computer(N)?"); str = (char)System.in.read();/*first input */
if(str=='Y')
{
str = (char)System.in.read();
System.out.println("Test"+str);/*Y under Char*/
} }