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++;
}
}
}
所以我有另一个带有 main 方法的类,在该类中我调用 createNumbers() 、createColours() 、createBalls() 。当我运行程序时,我在 numere.remove(nr) 处得到一个 IndexOutOfBoundsException ,说索引:数字和大小:另一个数字..总是第二个数字小于第一个数字..为什么会发生这种情况?我错在哪里?
问题是 ArrayList.remove() 有两种方法,一种是 Object,另一种是 (int index)。当您使用整数调用 .remove 时,它正在调用.remove(int)
这会删除索引,而不是对象值。
作为对评论的回应,这里有更多信息。
线路int nr = numere.get(random.nextInt(numere.size())
返回value调用返回的索引处的对象的位置。下一行numere.remove(...)
尝试从 ArrayList 中删除该值。
您可以采用以下两种方法之一:
int idx = random.nextInt(numere.size());
int nr = numere.get(idx);
numere.remove(idx);
The .remove(int)
方法返回remove对象的值,你也可以这样做:
int idx = random.nextInt(numere.size());
int nr = numere.remove(idx);
当然,如果需要,您可以将这两行合并为一行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)