代码被终止而无需获取第二个用户输入

时间:2019-07-07 02:13:51

标签: java

代码过早终止,而没有接受第二个用户输入。

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);
            }

1 个答案:

答案 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

相关问题