我制作了一个程序,允许用户制作芝士汉堡,然后询问他们是否想要配菜,然后询问他们是否想要订购另一个芝士汉堡。当我运行该程序时,它会跳过最后一个 if else 语句。
String orderAnother = sc.nextLine();
if (orderAnother.equalsIgnoreCase("yes")) {
System.out.println("Great! Another cheeseburger is on its way!");
} else {
System.out.println("Okay! Thanks for stopping at The Burger Shack and have a great day!");
}
有什么我无法弄清楚的错误吗?感谢帮助!
最佳答案
because the Scanner#nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine
解决方案
要么触发一个空白的 nextLine()
来使用换行符,要么将 nextInt()
更改为 nextLine()
并将其解析为一个整数。
更多详细信息位于此处:Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
关于java跳过if else语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36273033/