【发布时间】:2020-10-27 04:21:46
【问题描述】:
我有一个问题。这些都不适用于我的代码。
当运行此代码时
sodaType = keyboard.next();
userInput(代码中称为sodaType)只保存“Root Beer”的第一部分,输出(“Root”)。
我用谷歌搜索了这个问题,然后
sodaType = keyboard.nextLine();
允许“空白”,但跳过用户输入,不输出任何内容,跳过 if 语句。
我在这个网站上找到了不同的答案
- How do I make Java register a string input with spaces?
- User Input not working with keyboard.nextLine() and String (Java)
- Scanner doesn't see after space
我很困惑为什么 nextLine() 对他们有用,以及我应该如何继续。
while(true) {
System.out.println("Please enter a brand of soda. ");
System.out.print("You can choose from Pepsi, Coke, Dr. Pepper, or Root Beer: ");
sodaType = keyboard.next();
System.out.println("sodatype" + sodaType);
if (sodaType.equalsIgnoreCase("pepsi") || sodaType.equalsIgnoreCase("coke") ||
sodaType.equalsIgnoreCase("dr pepper") || sodaType.equalsIgnoreCase("dr. pepper") ||
sodaType.equalsIgnoreCase("root beer"))
{
System.out.println("you chose " + sodaType);
break;
}
else {
System.out.println("Please enter an avaiable brand of soda. ");
}
}
【问题讨论】:
-
outputting nothing, skipping the if statement你确定你在输入后按了回车吗?
标签: java java.util.scanner user-input