zeldaelf1
zeldaelf1

Reputation: 3

Trying to display a random card in a weird way with java

Right now I am trying to display a random card after defining a full deck. I was wondering if something along the lines of:

g.drawImage( card (int) * (Math.random() * 52), 10, this);

will work. When I try to compile this, I get the following error:

 '.class' expected

 g.drawImage( card (int) * (Math.random() * 52), 10, this);

What I am trying to do here is since I have declared 52 cards named card0 - card51, I was trying to see if I could just write card then get a random number from 0 - 51 next to card.

I was wondering if this is a legitimate way of displaying a random card or, if I should go back to the drawing board.

I am a beginner in java and, do not understand many terms so please, try to keep your answers simple.

Thanks for all the help in advance.

Upvotes: 0

Views: 72

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500825

No, that's not the way Java works. You can't use variable names determined at execution time.

Instead of having 52 separate variables, you should have an array or a collection:

private final Random random = new Random();
private final Card[] cards = new Card[52];
// Populate the array in the constructor, or wherever

...

// When you want to draw the card...
g.drawImage(cards[random.next(52)], 10, this);

Upvotes: 4

Related Questions