0

它在 IF 语句中有效,但在 ELSE 语句中,我必须输入 4 个响应才能打印出来。有任何想法吗?我知道我需要以某种方式清除缓冲区。

System.out.println("Would you like to play a game? (Y/N)");
        if(scanInput.next().equalsIgnoreCase("y")||scanInput.next().equalsIgnoreCase("Y")) {

        System.out.println("let's play");
    }

    else if (scanInput.next().equalsIgnoreCase("n") || scanInput.next().equalsIgnoreCase("N")){

        System.out.println("Goodbye");
    }
4

2 回答 2

5

刚读过InputStream一次:

String query = scanInput.next();
if (query.equalsIgnoreCase("y")) {
    System.out.println("let's play");
} else if (query.equalsIgnoreCase("n")) 
    System.out.println("Goodbye");
} // handle case where not Y or N ...

请注意,不需要多个String#equalsIgnoreCase表达式。在这里也scanInput.nextLine() 可能最好使用换行符。

于 2013-02-20T18:25:43.530 回答
0

这是因为您next()四次调用扫描仪的方法。此外,重点equalsIgnoreCase()是您不需要同时测试yY

System.out.println("Would you like to play a game? (Y/N)");
String x = scanInput.next();
if(x.equalsIgnoreCase("y")) {
    System.out.println("let's play");
}
else if (x.equalsIgnoreCase("N"))    
    System.out.println("Goodbye");
于 2013-02-20T18:27:03.363 回答