所以我正在编写一个程序,在一个套牌中随机挑选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);
}
}
它似乎是一个简单的问题,但我完全忘了怎么做。任何帮助表示赞赏。谢谢!
答案 0 :(得分:0)
您需要让paint
方法接受String[]
。然后,当您致电paint
时,您可以传入数组。
例如:
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);
}
}
答案 1 :(得分:0)
将String[] cardSelection;
声明为实例变量(在类声明旁边)。
然后,在getCards()方法中实例化数组:
cardSelection = new String[10];