我知道这已被要求死亡,但我还没有搜索并找到一个与我相似的案例,所以我想我会问......我这里有这个小代码......
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()问题时执行此操作!?
答案 0 :(得分:1)
仅在scan.nextLine()
之后拨打额外的scan.nextInt()
,而不是在scan.nextLine()
之后。使用额外scan.nextLine()
的想法是跳到换行符并转到下一行(因为scan.nextInt()
不这样做。)