static ArrayList<Integer> usedArray = new ArrayList<Integer>();
public static void arrayContents(){
usedArray.add(2, 2);
usedArray.add(1, 1);
}
public static void app(){
Random generator = new Random();
int randomNumber = generator.nextInt(usedArray.size());
System.out.println(usedArray);
System.out.println(randomNumber);
if(randomNumber == 2){
score();
question2();
usedArray.remove(2);
app();
}
.add(2, 2)
我得到一個錯誤:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
然而,使用
.add(2)
0生成作爲數組的一部分,儘管它不是一個值陣列。數組默認情況下總是包含0,並且有什麼方法可以解決這個問題,這樣0就不會產生爲隨機數?
請閱讀類'javadoc在使用之前。 –
爲什麼你使用基於索引的add? .add(index,object)而不是.add(object) –
'ArrayLists'有* 0-based *索引(即)起始索引爲'0',最後一個索引爲'list.size() - 1 '。 – SudoRahul