2016-07-07 23 views
0
String[] lvl15={"Twin", "Flank Guard", "Sniper", "Machine Gun"}; 
    String[] lvl30={"", "Triple Shot", "Quad Tank", "Twin Flank", "Tri-Angle", "Assasin", "Overseer", "Hunter", "Destroyer", "Gunner", ""}; 
    String[] lvl45={"Triplet", "Penta Shot", "Octo Tank", "Triple Twin", "Overlord", "Necromancer"}; 

    int index15; 
    int index30; 
    int index45; 

    index15=rand.nextInt(lvl15.length); 
    switch(index15){ 
     case 0: class15="Twin"; 
      break; 
     case 1: class15="Flank Guard"; 
      break; 
     case 2: class15="Sniper"; 
      break; 
     case 3: class15="Machine Gun"; 
      break; 
    } 

    if(class15=="Twin"){index30=rand.nextInt(3)+1; class30=lvl30[index30];} 
    if(class15=="Flank Guard"){index30=rand.nextInt(4)+2; class30=lvl30[index30];} 
    if(class15=="Sniper"){index30=rand.nextInt(7)+5; class30=lvl30[index30];} 
    if(class15=="Machine Gun"){index30=rand.nextInt(9)+8; class30=lvl30[index30];} 

有我的代碼。出於某種原因,它想出了這個錯誤有時隨機工具不工作,並導致錯誤

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11 
    at diepiogen.DiepIOGen.main(DiepIOGen.java:54) 
    C:\Users\******\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 
    BUILD FAILED (total time: 0 seconds) 

所以有人可以幫助,因爲它看起來這是沒有理由的方式行54,如果(class15 ==「狙擊手」){index30 =蘭特.nextInt(7)5; class30 = lvl30 [index30];}

現在我只是添加填充,因爲否則我不能發佈此。

+1

您的數組大小爲11,因此索引從0到10 ...錯誤告訴您您正在使用不存在的索引「11」。 – sinclair

+3

if(class15 ==「Twin」)'[我如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) - 我知道這個部分現在可能適用於你,因爲你正在比較字符串文字(在編譯時已知這個商品),但是你應該停止使用'=='來比較字符串(特別是如果你將開始比較創建的字符串在運行時)。 – Pshemo

+0

你超過了隨機產生的數組範圍303 – Li357

回答

0

從rand.nextInt數學結果(7)將是0-6之間,所以隨機當你6和添加5,則要去有11.您的陣列具有11元素,但第11具有10 索引因此,將代碼 從index30=rand.nextInt(7)+5 更改爲index30=rand.nextInt(7)+4 數組索引超出了界限。請參閱java文檔:http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt()

+0

我怎樣才能讓它產生一個範圍內的數字,如3-6。 – mobinblack

+0

'rand.nextInt(7)'和if語句。 'int random = rand.nextInt(7);如果(隨機<4)隨機= rand.nextInt(7);'...這是不是最好的解決方案,其中概率太低。或甚至更好的'rand.nextInt(4)+ 3',但你必須考慮哪一個是包括和排他的 – BigBugNoob

0

您的索引超出了數組的範圍。 來自java的文檔:http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt() 它表明nextInt(n)將得到一個新的整數,它包含0到n的範圍(意思是從0到n-1)。你所做的列表(lvl30)有11個條目,所以如果你將5加到0 &6之間的一個int,有時你會得到11,這是超出界限的。