2013-02-14 50 views
1

我知道这已被要求死亡,但我还没有搜索和找到一个很像我的案例,所以我想我会问...我有这里这个小码...scanner nextLine()允许一个或两个单词的输入

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()的问题!?

回答

1

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

Scanner issue when using nextLine after nextXXX

+0

但后来我得到这样的输出这个“你会喜欢你的新配方的名称是什么?有多少成分没有这个配方有吗?”都在同一行! – Sherifftwinkie 2013-02-14 01:57:35

+0

@Sherifftwinkie在'name = scan.nextLine();'之前,你似乎使用了扫描器,并且缓冲区中还有一个换行字符未被占用。 – 2013-02-14 02:03:22

+0

optionAnswer = scan.next();这可能是罪魁祸首吗?我认为这不重要,因为它只查找1个字母,并且始终只能得到1个字母作为输入 – Sherifftwinkie 2013-02-14 02:06:48

相关问题