2016-04-14 86 views
1
import java.util.Random; 
import java.util.ArrayList; 
public class Game { 
ArrayList<Integer> numere = new ArrayList<>(); 
ArrayList<Bila> balls = new ArrayList<Bila>(); 
ArrayList<String> culori = new ArrayList<>(); 
Random random = new Random(); 
int nrBalls=0; 
public void createColours(){ 
    for(int i=0;i<7;i++){ 
     culori.add("Portocaliu"); 
     culori.add("Rosu"); 
     culori.add("Albastru"); 
     culori.add("Verde"); 
     culori.add("Negru"); 
     culori.add("Galben"); 
     culori.add("Violet"); 
    } 
} 
public void createNumbers(){ 
    for(int i=1;i<50;i++){ 
     numere.add(i); 
     System.out.print(numere.size()); 
    } 
} 
public void createBalls(){ 
    while(nrBalls<36){ 
     int nr =numere.get(random.nextInt(numere.size())); 
     numere.remove(nr); 
     String culoare =culori.get(random.nextInt(culori.size()-1)); 
     culori.remove(culoare); 
     balls.add(new Bila(culoare,nr)); 
     nrBalls++; 
    } 
} 
} 

所以我有另一個類的主要方法,並在I類調用createNumbers(),createColours(),createBalls()。當我運行程序我得到numere.remove IndexOutOfBoundsException異常(nr)說索引:一個數字和大小:另一個數字..總是第二個數字小於第一個數字。爲什麼發生這種情況?我錯在哪裏?從ArrayList中移除整數IndexOutOfBoundsException異常

回答

1

問題是ArrayList.remove()有兩個方法,一個是對象,另一個是(int索引)。當您使用整數調用.remove時,它將調用.remove(int),它將刪除索引,而不是對象值。

迴應評論,這是一個更多的信息。

int nr = numere.get(random.nextInt(numere.size())由調用返回的索引處返回對象的線。下一行numere.remove(...)嘗試從ArrayList中移除該值。

你可以做以下兩種方法之一:

int idx = random.nextInt(numere.size()); 
int nr = numere.get(idx); 
numere.remove(idx); 

.remove(int)方法返回對象的刪除的價值,你也可以這樣做:

int idx = random.nextInt(numere.size()); 
int nr = numere.remove(idx); 

當然,你也可以鞏固那些如果需要,可將兩條線分成一條。

+0

是的,我希望它刪除我在那個位置的數組列表中的數字 –

+0

@BaiRadule提供了一個更新的答案和更多的解釋。本質上,原始代碼從數組中取**值**,然後嘗試從索引中刪除**值**而不是索引位置。 – KevinO

+0

謝謝你,這是我正在尋找的答案 –

1

numere - ArrayList中僅包含intergers 1至49.

numere.remove(NR); - 這裏nr可以是整數範圍內的任何數字。因爲它是由隨機函數創建的。所以這是拋出一個錯誤。您只能刪除數組列表中的元素。否則程序將拋出異​​常

0

remove(int)將刪除給定索引處的元素,而不是等於給定值的元素。並且還返回刪除的元素,所以你可以簡單地做:

int nr = numere.remove(random.nextInt(numere.size())); 

您可以爲您culoare做同樣的:

String culoare = culori.remove(random.nextInt(culori.size())); 

只是介意,如果參數是零Random.nextInt(int)將拋出一個異常(如果你的列表是空的)。

+0

是的,但如果隨機數是爲前32比我的數組中的32號索引將是31,所以如果我把numere.size() - 1將刪除確切的數字,我想..但它仍然給我同樣的錯誤 –

+0

我的列表將不會是空的,因爲我只有35個數字..而我的數組有49個 –

相關問題