0

所以我正在编写一个程序,它随机挑选一副牌中的 10 张牌并显示它们。但是,我不知道如何将用于存储随机卡片的数组传递给打印卡片的方法。这是我的代码:

import java.awt.Graphics;
import java.awt.Color;
import java.awt.Image;
import java.applet.Applet;
import java.lang.Math;
import java.util.Random;

public class unit12Assignment extends Applet
{
    Image card1 ... card52;

public void init()
{
    card1 = getImage( getDocumentBase(), "c1.gif" );
        ...
    card52 = getImage( getDocumentBase(), "sk.gif" );
}

public void getCards(String[] cardSelection)
{
    String cardNumber; 
    double cardRandom;
    int cardRandomNumber;
    Random ran = new Random();
            cardSelection = new String[10]

    for (int number = 0; number <=  9; )
    {
        cardRandom = ran.nextInt(52) + 1;
        cardRandomNumber = (int) Math.round( cardRandom );

        if ( cardRandomNumber > 0 && cardRandomNumber <= 52 )
        { 
            cardNumber =  "card" + cardRandomNumber;
            number++;
        }
    }   
}

    // i wanna pass it to this method
public void paint(Graphics g)
{
    setBackground( Color.green );
    g.drawImage( cardSelection[0], 10, 10, this);
    g.drawImage( cardSelection[1], 90, 10, this);
    g.drawImage( cardSelection[2], 170, 10, this);
    g.drawImage( cardSelection[3], 250, 10, this);
}

}

这似乎是一个简单的问题,但我完全忘记了如何去做。任何帮助表示赞赏。谢谢!

4

2 回答 2

0

声明String[] cardSelection;为实例变量(在类声明旁边)。

然后,在 getCards() 方法中实例化数组:

cardSelection = new String[10];
于 2012-09-03T15:12:32.587 回答
0

You need to make the paint method accept a String[]. Then you can pass in your array when you call paint.

For example:

public void main(String[] args) {
  String[] myArray = makeArray();
  printArray(myArray);
}   

public String[] makeArray() {
  return new String[] {"element0", "element1", "element2"};
}   

public void printArray(String[] array) {
  for (String element : array) {
    System.out.println(element);
  }   
}
于 2012-09-03T15:10:49.993 回答