2015-04-02 14 views
1

我的程序編譯,但是當我運行它時,它給了我一個IndexOutOfBoundsException。我想知道它有什麼問題,因爲我無法看到它。我的程序應該由用戶輸入並將其添加到ArrayList。如果我的錯誤對你顯而易見,我很抱歉,但我在使用ArrayLists方面相對較新。謝謝!我的ArrayList究竟出了什麼問題?

ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>(); 
int counter = 0; 
int i = 0; 
Scanner in = new Scanner(System.in); 
int input = in.nextInt(); 

while(i < 5) 
{ 
    input = in.nextInt(); 
    if(input != 0){ 
     arr.get(i).set(counter++, input); 
    } 
    else{ 
     arr.get(i).set(counter++, input); 
     i++; 
     counter = 0; 
    } 
} 

System.out.println(arr); 
+2

你從不向「arr」添加任何東西。你期望'arr.get(i)'在一個空的'List'上調用時怎麼做? – azurefrog 2015-04-02 21:59:25

+0

爲什麼你想要一個嵌套數組列表? – 2015-04-02 21:59:27

+0

你想創建一個沒有負數的數組列表嗎? – Arlind 2015-04-02 22:01:27

回答

3

當您創建ArrayListArrayList S,最初,也有包含在arr沒有ArrayList秒。所以任何撥打get的電話都將失敗,並顯示IndexOutOfBoundsException

首先,將初始內部ArrayList添加到arr

然後,在while循環,get當前內ArrayList,你在做什麼,只是叫add多項追加到列表的末尾。否則,您會在ArrayList的內部獲得IndexOutOfBoundsException。再次,你創建的ArrayList最初是空的。

當用戶進入0,然後add另一ArrayList當你遞增i(除非i已經處於最後的希望值),爲用戶添加數字下次表做準備。

+0

因此,如果我要使ArrayList ArrayList > arr = new ArrayList >(5)的初始創建;'會這樣嗎?因爲我仍然收到一個IndexOutOfBoundsError。 – BreadCat 2015-04-03 00:13:45

+0

不,這只是將外部'ArrayList'的初始_capacity_設置爲5.如果您只是對代碼進行更改,那麼外部'ArrayList'中將不會有任何內容。如果你願意,你可以做出改變,但你仍然需要在我的答案中做出改變。 – rgettman 2015-04-03 00:17:32

0

您正在創建列表的列表,並且都是空的。此外,您正在使用實際用於替換特定位置列表中的對象的「set」方法。

因此,它看起來像你想從用戶採取的輸入,如果值爲0,你只是想忽略它。以下是您的更新示例。

ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>(); 
    int i = 0; 
    Scanner in = new Scanner(System.in); 
    int input = 0; 
    while(i < 5){ 
     input = in.nextInt(); 
     if(input != 0){ 
      arr.add(new ArrayList<Integer>()); 
      arr.get(i).add(input); 
      i++; 
     } 

    } 

    System.out.println(arr); 

如果你只是想創建一個整數列表,那麼你不需要創建列表的列表。您可以通過僅創建一個整數列表來實現。

ArrayList<Integer> arr = new ArrayList<Integer>(); 
    int i = 0; 
    Scanner in = new Scanner(System.in); 
    int input = 0; 
    while(i < 5){ 
     input = in.nextInt(); 
     if(input != 0){ 
      arr.add(input); 
      i++; 
     } 

    } 

    System.out.println(arr);