next() 不允许 "white space" 和 nextLine() 一起跳过 "sodaType"

next() does't allow "white space" and nextLine() skips "sodaType" all together

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

当运行此代码与

sodaType = keyboard.next();

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

我用谷歌搜索了这个问题

sodaType = keyboard.nextLine();

允许“白色 space”,但跳过 userInput,不输出任何内容,跳过 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. ");

        }
    }

所以当你写 .next() 这个函数读取 String 并读取直到遇到 white space
因此,当您编写此代码并将输入作为 root beer 时,它将 read-only root 导致在那之后 root 有一个 white space 告诉 java 停止阅读原因可能是用户想结束阅读。

sodaType = keyboard.next();

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

这样的输入时
sodaType = keyboard.nextLine();

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

这是因为扫描仪通过将输入分成 'tokens' 和 'delimiters' 序列来工作。开箱即用,'one or more whitespace characters' 是定界符,因此,输入:

Root Beer
Hello World
5

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

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

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

这是一个匹配换行符的正则表达式,无论 OS。

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