2016-01-08 7 views
0

我有這段代碼應該通過掃描器的next()或nextLine()方法將字符串值添加到arrayList。 next()的問題在於它忽略了第一個空格之後的所有內容,所以我應該使用nextLine()方法。 nextLine()的問題在於它沒有記錄輸入,而是在arrayList中存儲了一些空格。下面的代碼:Java:nextLine()跳過輸入並向arrayList添加空格

System.out.println("\nWhat is your idea? ");     
String i = in.nextLine();        
in.nextLine(); 
meals.add(i);  
System.out.println("\n" + i + " has been entered into the idea pool. \n"); 
System.in.read(); 

我添加了額外的「in.nextLine()」的首字母后「字符串I = in.nextLine()」,因爲這是我發現,當我研究這個問題,但沒有關係的唯一的解決方法它不適合我,它只是存儲了一些空白空間。而且,System.in.read();在結尾處僅存在,以便它在輸入後不會向前跳躍。

這裏就是上述樣品裝配到代碼:

ArrayList<String> meals = new ArrayList<String>(); 
String select = ""; 
while(!select.equals("")){ 
    System.out.println("What would you like to do?"); 
    System.out.println("1. <Irrelevant>"); 
    System.out.println("2. Enter an idea"); 
    System.out.println("3. <Irrelevant>"); 
    System.out.println("4. <Irrelevant>"); 
    System.out.println("Q. <Irrelevant>"); 

    select = in.next(); 

    switch(select){ 
     case "1": 
      //Some stuff here. 
     case "2": 
      //Here's where the above problem fits into. 
     case "3": 
      //More stuff here 
     //and so on...  
    } 
} 
+1

爲什麼使用'System.in.read();'?沒有意義。 –

回答

0

爲什麼要面對這樣的問題的原因是因爲使用的是首先next()方法來讀取輸入,並且進一步輸入你正在使用nextLine()。

next()接受輸入,並且輸入指針與當前輸入保持同一行。

因此,只要您輸入您的選擇並按回車,選擇被保存到select變量,但輸入指針仍然在同一行。您應該使用nextLine()將指針移至新行。

然後你應該使用任何數量的nextLine()來接收多行。

另外,從case 2語句中刪除多餘的nextLine()方法調用。移除System.in.read()也是如此,因爲你的問題已經解決了。

ArrayList<String> meals = new ArrayList<String>(); 
String select = ""; 
while(!select.equals("")){ 
System.out.println("What would you like to do?"); 
System.out.println("1. <Irrelevant>"); 
System.out.println("2. Enter an idea"); 
System.out.println("3. <Irrelevant>"); 
System.out.println("4. <Irrelevant>"); 
System.out.println("Q. <Irrelevant>"); 

select = in.next(); 
in.nextLine(); // add this extra line in your code 
switch(select){ 
    case "1": 
     //Some stuff here. 
    case "2": 
     System.out.println("\nWhat is your idea? ");     
     String i = in.nextLine();        
     meals.add(i);  
     System.out.println("\n" + i + " has been entered into the idea pool. \n"); 
    case "3": 
     //More stuff here 
    //and so on...  
} 
+0

這真的有竅門。我從來不知道如果你使用next()或nextLine(),你將不得不繼續使用它。感謝您的幫助。 –

+0

適當的行動本來會投票結束,因爲重複的很多。這裏是一個:http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods?rq=1 –

+0

爲什麼不只是使用'select = in.nextLine( )'這裏,完全擺脫'in.next()'? – Tricky12