Java 如何清除缓冲区以使其正常工作?

Java 如何清除缓冲区以使其正常工作?,java,Java,它在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

它在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");
    }

只需从
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
表达式指定表达式。另外,这里可能更喜欢使用换行符的
scanport.nextLine()

只需从
输入流中读取一次:

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()
在这里可能更适合使用换行符。

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

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

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

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