java跳过if else语句

标签 java if-statement

我制作了一个程序,允许用户制作芝士汉堡,然后询问他们是否想要配菜,然后询问他们是否想要订购另一个芝士汉堡。当我运行该程序时,它会跳过最后一个 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!");
}

有什么我无法弄清楚的错误吗?感谢帮助!

最佳答案

The problem is

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/

相关文章:

c - 使用 for 循环打印特定的 "non-vowel, vowel, non-vowel"单词

c - if 语句是否可以判断是否未输入某些内容?

if-statement - 如何在 Karate 中使用 if 条件

java - 在不使用渲染器的情况下在 JTable 中绘制单个单元格(或单个行)

java - web.xml 中未经授权的页面配置

java - 方法和循环中的内联大括号 block

if-statement - 新 Racket : why is the if statement affecting the return?

Java 字符串检查

java - Unix 时间戳(UTC)和 Java UTC 相同吗?我们可以比较吗?

java - 后台线程完成后返回 Android Activity