我一直在尝试创建一个小程序来洗牌并显示前十张。它一直在工作,直到我尝试添加代码以防止卡重用。它不断返回越界异常。
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Random;
public class Main extends Applet
{
Image card1;
Image card2;
Image card3;
Image card4;
Image card5;
Image card6;
Image card7;
Image card8;
Image card9;
Image card10;
public void init()
{
Random random = new Random();
String cards[][] = {{"c1.gif", "c2.gif", "c3.gif", "c4.gif", "c5.gif", "c6.gif", "c7.gif", "c8.gif", "c9.gif", "c10.gif", "cj.gif", "ck.gif", "cq.gif"}, {"s1.gif", "s2.gif", "s3.gif", "s4.gif", "s5.gif", "s6.gif", "s7.gif", "s8.gif", "s9.gif", "s10.gif", "sj.gif", "sk.gif", "sq.gif"}, {"d1.gif", "d2.gif", "d3.gif", "d4.gif", "d5.gif", "d6.gif", "d7.gif", "d8.gif", "d9.gif", "d10.gif", "dj.gif", "dk.gif", "dq.gif"}, {"h1.gif", "h2.gif", "h3.gif", "h4.gif", "h5.gif", "h6.gif", "h7.gif", "h8.gif", "h9.gif", "h10.gif", "hj.gif", "hk.gif", "hq.gif"}};
int selectedCard[] = new int[10];
int selectedSuit[] = new int[10];
int suit = random.nextInt(4);
int card = random.nextInt(13);
boolean newCard = false;
for(int x = 0; x < 10; x++)
{
while(newCard = false)
{
newCard = true;
suit = random.nextInt(4);
card = random.nextInt(13);
for(int y = 0; y < x; y++)
{
if(selectedCard[y] == card && selectedSuit[y] == suit)
{
newCard = false;
}
}
}
selectedCard[x] = card;
selectedSuit[x] = suit;
}
card1 = getImage(getDocumentBase(), cards[selectedSuit[1]][selectedCard[1]]);
card2 = getImage(getDocumentBase(), cards[selectedSuit[2]][selectedCard[2]]);
card3 = getImage(getDocumentBase(), cards[selectedSuit[3]][selectedCard[3]]);
card4 = getImage(getDocumentBase(), cards[selectedSuit[4]][selectedCard[4]]);
card5 = getImage(getDocumentBase(), cards[selectedSuit[5]][selectedCard[5]]);
card6 = getImage(getDocumentBase(), cards[selectedSuit[6]][selectedCard[6]]);
card7 = getImage(getDocumentBase(), cards[selectedSuit[7]][selectedCard[7]]);
card8 = getImage(getDocumentBase(), cards[selectedSuit[8]][selectedCard[8]]);
card9 = getImage(getDocumentBase(), cards[selectedSuit[9]][selectedCard[9]]);
card10 = getImage(getDocumentBase(), cards[selectedSuit[10]][selectedCard[10]]);
}
public void paint(Graphics g)
{
g.drawImage(card1, 30, 30, this);
g.drawImage(card2, 30, 150, this);
g.drawImage(card3, 120, 30, this);
g.drawImage(card4, 120, 150, this);
g.drawImage(card5, 210, 30, this);
g.drawImage(card6, 210, 150, this);
g.drawImage(card7, 300, 30, this);
g.drawImage(card8, 300, 150, this);
g.drawImage(card9, 390, 30, this);
g.drawImage(card10, 390, 150, this);
}
}