2016-04-14 85 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个 –

相关问题