2013-02-14 67 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

相關問題