【问题标题】:next() does't allow "white space" and nextLine() skips "sodaType" all togethernext() 不允许“空白”并且 nextLine() 一起跳过“sodaType”
【发布时间】:2020-10-27 04:21:46
【问题描述】:

我有一个问题。这些都不适用于我的代码。

当运行此代码时

sodaType = keyboard.next();

userInput(代码中称为sodaType)只保存“Root Beer”的第一部分,输出(“Root”)。

我用谷歌搜索了这个问题,然后

sodaType = keyboard.nextLine();

允许“空白”,但跳过用户输入,不输出任何内容,跳过 if 语句。

我在这个网站上找到了不同的答案

我很困惑为什么 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


【解决方案1】:

这是因为扫描器通过将输入分成一系列“标记”和“分隔符”来工作。开箱即用,“一个或多个空白字符”是分隔符,因此,输入:

Root Beer
Hello World
5

由 5 个令牌组成:[RootBeerHelloWorld5]。你想要的是这形成了 3 个令牌:[Root BeerHello World5]。

很简单:告诉扫描仪您打算将换行符作为分隔符,而不仅仅是任何空格:

Scanner s = new Scanner(System.in);
s.useDelimiter("\r?\n");

这是一个正则表达式,无论操作系统如何,都会匹配换行符。

在扫描仪中将nextLine() 与任何其他下一个方法混合会导致痛苦和痛苦,所以,不要这样做。忘记 nextLine 存在。

【讨论】:

  • 谢谢!这正是我所需要的!
【解决方案2】:

因此,当您编写 .next() 时,此函数会读取 String 并读取直到遇到 white space
因此,当您编写此代码并以root beer 提供输入时,它将只读root,因为在root 之后有一个white space 告诉java 停止读取,因为可能是用户想要结束读取。

sodaType = keyboard.next();

这就是引入.nextLint() 的原因,因为它会读取整行,因为它包括white spaces。 因此,当您编写并提供诸如root beer 之类的输入时

sodaType = keyboard.nextLine();

它将存储为root beer
如果您将输入输入为 root beer ,它将存储为 root beer
注意:空格的确切数量。

【讨论】:

  • 正确答案是useDelimiter;如果用户输入空格,混合 nextLine 和 next 会导致大问题。我知道“使用 nextLine!”是常见的建议。这是常见的坏建议。
  • @rzwitserloot 谢谢你,我会把这个添加到我的知识中。
猜你喜欢
  • 2010-10-22
  • 2021-11-11
相关资源
最近更新 更多