在下面的代码中我得到了ArrayIndexOutOfBoundsException。我是Java的新手,没有得到导致它超出界限的线索。我调试此代码,输入4个条目后终止。
String[] suit = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
String[] deck = new String[suit.length * rank.length];
int i = (int)(Math.random()*rank.length);
int j = (int)(Math.random()*suit.length);
System.out.println(rank[i]+" of "+suit[j]);
for(int k=0; k<suit.length; k++){
for(int l=0; l<rank.length; l++){
//on the following line.
deck[rank.length*k + l] = rank[k]+ " of "+suit[l];
}
}
for(String s : deck){
System.out.println(s);
}
答案 0 :(得分:1)
我很确定你把这些变量混淆了
deck[rank.length*k + l] = rank[k]+ " of "+suit[l];
应该是
deck[rank.length*k + l] = rank[l]+ " of "+suit[k];
答案 1 :(得分:0)
问题的原因是您应该使用k
索引而不是l
:
deck[rank.length*k + l] = rank[k]+ " of "+suit[l];
像这样:
deck[rank.length*k + l] = rank[k]+ " of "+suit[k];
因为rank.length
>
suit.length
因为此索引suit[4]
中的数组中没有数据。