我的java代码有问题。我想将一个数组复制并复制到一个新数组。它总是在java.lang.ArrayIndexOutOfBoundsException
上给我错误代码:
public void SetCard(int usrSet)
{
//define 52card with number and shape
String[] cards = {"1a","1d", "1h", "1s", "2a", "2d", "2h", "2s"};
//set to an global array
deckCards = null;
//deckCards = new String[cards.length];
//deckCards = cards;
int setLength = cards.length;
String temp = "";
if (usrSet >= 1)
{
setLength = setLength * usrSet - 1;
int a = 0;
deckCards = new String[setLength];
System.out.println("Deck Cards now is " + deckCards.length);
for (int i = 0; i < usrSet; i++)
{
for(int j = 0; j < cards.length; j++)
{
temp = cards[j];
System.out.println("Position SetL = "+ a + "J is " + j + "Temp = "+ temp);
deckCards[a] = temp;
a++;
}
}
//System.out.println(Arrays.toString(deckCards));
}
}
答案 0 :(得分:0)
你必须删除“ - 1”:
setLength = setLength * usrSet - 1;
所以它变成了
setLength = setLength * usrSet;
答案 1 :(得分:0)
如果usrSet大于1,您的代码将给出ArrayIndexOutOfBoundsException。 如果你的目的只是制作一个数组的副本,我不知道你为什么要做这么多事情。可能以下代码就足够了:
String[] deckCards = new String[setLength];
for(int j = 0; j < cards.length; j++){
temp = cards[j];
deckCards[j]= temp;
}
如果您可以自由使用其他api,请尝试探索java.util.Arrays
答案 2 :(得分:0)