2013-03-23 38 views
0

我想用此功能編寫程序: 用戶將輸入他有多少事情。他會輸入這些東西,東西將被添加到列表中。 我做了這個代碼:LinkedList中的list.add(String)對我無法正常工作

public class lists { 
public static void main(String[] args){ 
    Scanner input = new Scanner(System.in); 
    LinkedList<String> list= new LinkedList<String>(); 
    System.out.println("How many things you have?"); 
    int size=input.nextInt(); 
    LinkedList<String> list= new LinkedList<String>(); 
    System.out.println("Enter those things"); 
    for(int c=1;c<=size;c++) list.add(input.nextLine().toString());  
     System.out.printf("%s",list); 

} 

}

例如輸出爲5號看起來是這樣的:

[, 1st Inputed, 2nd Inputed,3rd Inputed, 4nd inputed] 

我想知道爲什麼在列表中的第一個字符串是空的,它讓我輸入更少的東西,我想要的。感謝您的幫助。

+7

你的程序不會編譯,因爲變量'list'被聲明瞭兩次.. – 2013-03-23 18:16:59

回答

1

您的代碼應該是這樣的:

public class lists { 
    public static void main(String[] args){ 
     Scanner input = new Scanner(System.in); 
     System.out.println("How many things you have?"); 
     int size=input.nextInt(); 
     LinkedList<String> list= new LinkedList<String>(); 
     System.out.println("Enter those things"); 
     for(int c=0 ;c < size; c++) 
     { 
      String s = input.next();//use next() instead of nextLine() 
      list.add(s);  
     } 
      System.out.printf("%s",list); 

     } 
    } 

Scanner.nextLine()作爲正式文件中描述的是:

此掃描器執行當前行,並返回輸入的是 被跳過。該方法返回當前行的其餘部分, (不包括結尾處的任何行分隔符)。該位置設置爲下一行開頭的 。

nextInt()被調用後,它沒有正確終止分配的內存行。所以當第一次調用nextLine()時,它實際上是終止了其中實際上有值的上一行 - 通過nextInt()輸入,而不是輸入新的String值。這就是的Stringlist爲空的原因。因此,爲了進行讀取輸入的值,而不是之前的空行(因爲nextInt()返回的值未結束),你可以用它根據官方文件Scanner.next()指出:

發現和從該掃描儀返回下一個完整的令牌。

0

的問題是,input.nextInt()不消耗換行符,所以第一input.nextLine()返回一個空字符串。

有幾種方法可以解決此問題。我將把它作爲一個練習來找出如何最好地做到這一點。