java - 扫描仪 nextLine() 允许输入一个或两个单词

标签 java string input

我知道这已经被要求死了,但我还没有搜索并找到一个与我的情况非常相似的案例,所以我想我会问...我这里有这个小代码...

System.out.print("What would you like the name of your new recipe to be? ");
        Recipe tempRecipe = new Recipe(name);
        name = scan.nextLine();
        scan.nextLine();
        tempRecipe.setName(name);

        System.out.print("How many ingredients does this recipe have? ");
        ingredientCount = scan.nextInt();
        scan.nextLine();

现在显然我遇到了 println 语句位于同一行且不允许输入的问题,因此我引入了 scan.nextLine() 来解决问题。但现在的问题是,当我读到其中的内容时,由于 nextLine() 太多,我只看到了空白!如果我将其更改为 name = scan.next() 我只能读取一个单词,并且如果需要的话我需要能够不加区别地读取 1 个或 2 个单词,了解以下代码是这些行也可能会有所帮助

Ingredient tempIngredient = new Ingredient(name, quantity, null);

            System.out.print("Enter the name of ingredient number " + (i+1) + ": ");
            name = scan.nextLine();
            tempIngredient.setName(name);

            System.out.print("Enter the quantity of ingredient number " + (i+1) + ": ");
            quantity = scan.nextDouble();
            scan.nextLine();
            tempIngredient.setQuantity(quantity);

            System.out.print("Enter the unit of measurement of ingredient number " + (i+1) + ": ");
            unit = scan.nextLine();
            tempIngredient.setUnit(UnitOfMeasurement.valueOf(unit));

如果需要,tempRecipes 名称和 tempIngredients 名称都需要能够容纳 1 或 2 个单词,我该如何在解决 nextLine() 问题的同时做到这一点!?

最佳答案

仅在 scan.nextInt() 之后调用额外的 scan.nextLine(),而不是在 scan.nextLine() 之后调用。使用额外的 scan.nextLine() 的想法是跳到换行符并转到下一行(因为 scan.nextInt() 不会这样做)。

参见Scanner issue when using nextLine after nextXXX

关于java - 扫描仪 nextLine() 允许输入一个或两个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14866493/

相关文章:

java - 尝试为我的代码获取正确的值答案

java - 如何在java中使用StrSubstitutor进行嵌套Map

javascript - 使用 javascript 进行简单语法高亮显示

c# - 想要用给定的十六进制代码值形成一个字符串

java - 在命令窗口中运行 rcp 时如何从命令行获取参数?

java - 授权谷歌日历API适用于个人帐户,但不适用于谷歌域帐户

c++ - 如何转换包含十六进制整数的字符串

java - 如何在java中从键盘输入一些单词

c++ - 为什么 std::getline() 在格式化提取后跳过输入?

html - 去除文本输入的内部阴影