代码过早终止,而没有接受第二个用户输入。
public static void main(String[] args)throws java.io.IOException {
// TODO Auto-generated method stub
char ch;
System.out.println("Press any key to throw a die and press Enter (or Q and Enter to quit)");
ch = (char) System.in.read();
if(ch == 'q'|| ch =='Q')
{
System.exit(0);
}
else
{
dieFace = (int)(Math.random() * max) +1;
System.out.println("You rolled a " + dieFace);
}
char pa;
System.out.println("Play Again? (Y or y) and Enter, any other key and Enter to Quit");
pa = (char) System.in.read();
if(pa == 'Y'|| pa =='y')
{
dieFace = (int)(Math.random() * max) +1;
System.out.println("You rolled a " + dieFace);
}
else
{
System.exit(0);
}
答案 0 :(得分:1)
该代码不接受第二次用户输入,这是由于第一次输入后,我们需要输入Enter
来结束第一次输入。就是这个问题,Enter
也是输入(ASCII码为10)。
我们需要尝试读出Enter
,以便我们可以等待新的输入。只需在第二次输入之前为System.in
添加更多阅读内容即可。
System.out.println("Press any key to throw a die and press Enter (or Q and Enter to quit)");
ch = (char) System.in.read();
if(ch == 'q'|| ch =='Q')
{
System.exit(0);
}
else
{
dieFace = (int)(Math.random() * max) +1;
System.out.println("You rolled a " + dieFace);
}
char pa;
System.out.println("Play Again? (Y or y) and Enter, any other key and Enter to Quit");
int enterKey = System.in.read();//this is the enter key char
pa = (char) System.in.read();
if(pa == 'Y'|| pa =='y')
{
dieFace = (int)(Math.random() * max) +1;
System.out.println("You rolled a " + dieFace);
}
else
{
System.exit(0);
}
注意: int enterKey = System.in.read();//this is the enter key char
,用于读取输入内容。
建议:java.util.Scanner
可能更适合您,请查看Doc