2015-06-22 30 views
-8

我使用的是ArrayList來創建我需要在我的程序中管理的魚列表。
我遇到的問題是,當填寫進入魚類的數量列表時,我收到一個異常和程序崩潰。ArrayList OutOfBoundsException

這裏是我的代碼:

Random RandomGenerator = new Random(); 

Scanner sc = new Scanner(System.in); 

int simulation = 0; 

System.out.println("Veuillez entrer le nombre de poissons carnivores:"); 
nbre_c = sc.nextInt(); 
System.out.println("Veuillez entrer le nombre de poissons herbivores:"); 
nbre_h = sc.nextInt(); 
System.out.println("Veuillez entrer le nombre d'algues:"); 
nbre_a = sc.nextInt(); 

sc.close(); 


ArrayList<Herbivor> list_h = new ArrayList<Herbivor>(); 
ArrayList<Carnivor> list_c = new ArrayList<Carnivor>(); 
ArrayList<Algue> list_a = new ArrayList<Algue>(); 

while(simulation<100) 
{ 
    System.out.println("Début de la simulation: "); 
    int nb = nbre_c; 
    for(int i = 0; i<nb;i++) // Issue #`1` 
    { 
     Carnivor c = new Carnivor(); 
     list_c.add(c); 
    } 

    nb = nbre_h; 
    for(int i = 0; i<nb;i++) // Creation des Poissons Herbivores 
    { 
     Herbivor h = new Herbivor(); 
     list_h.add(h); 
    } 

    nb = nbre_a; 
    for(int i = 0; i<nb;i++) // Creation des Algues 
    { 
     Algue a = new Algue(); 
     list_a.add(a); 
    } 
} 
+1

異常的(完整)文本在哪裏?它引用了哪條線?你給你的程序輸入了什麼?回答基於不完整信息的問題是非常困難的。 – azurefrog

+0

這應該起作用。你沒有發佈的代碼是否發生異常? –

+0

沒錯對不起,這裏是控制檯輸出: ' Veuillez entrer樂農布雷迪奧斯泊松食肉動物: Veuillez entrer樂農布雷迪奧斯泊松食草動物: Veuillez entrer勒農佈雷D'Algues賓館:亮相德拉模擬: 異常在線程 「主」 java.lang.IndexOutOfBoundsException:索引:16,尺寸:10 \t在java.util.ArrayList.rangeCheck(ArrayList.java:635) \t在java.util.ArrayList.get(ArrayList的.java:411) \t at Ocean.main(Ocean.java:128)' – user2325855

回答

0

兩個小技巧:

1-變量RandomGenerator在代碼中沒有使用(但不是很重要)

2 - 模擬的值設置爲。 (非常重要)

我認爲注意第二個技巧可以解決你的問題。