我知道这已经被要求死了,但我还没有搜索并找到一个与我的情况非常相似的案例,所以我想我会问...我这里有这个小代码...
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()
不会这样做)。
关于java - 扫描仪 nextLine() 允许输入一个或两个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14866493/