2016-07-07 58 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,这是超出界限的。