So I am writing a program that randomly picks 10 cards in a deck and displays them. However, I can't figure out how to pass the array with I use to store the random cards to the method in which I print out the cards. This is my code:
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);
}
}
Its seems like a simple problem but I completely forgot how to do it. Any help is appreciated. Thanks!
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);
}
}
Declare String[] cardSelection;
as an instance variable (next to the class declaration).
Then, in the getCards() method instantiate the array:
cardSelection = new String[10];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.