I’m trying to learn Java and I wanted to make a very simple class that would randomly select 5 cards from a randomly generated deck of cards. I’m running into something that I feel should be a very simple issue to solve. Also, this is for a lab at the University I attend so if you are able to guide me without giving me blocks of code, that would be preferable.
This is the error I receive, and I understand why I receive it:
The type of the expression must be an array type but it resolved to Deck
Here is my code:
public static void main(String[] args) {
System.out.println(select(5));
}
public static Card[] select(int k)
{
Random rand = new Random(52);
Deck deck = new Deck(52);
Card[] hand = new Card[5];
for (int j = 0; j < 5; j += 1)
{
int index = rand.nextInt(52-j);
hand[j] = deck[index];
}
return hand;
}
The Deck.java and Card.java classes were provided by my instructor (who is unavailable during lab time).
I also recently realized this code is not going to do for me what I want it to do, however I still need to figure out the error I have above. If you wanted to help with the other issue I have, feel free to answer my explanation below but it’s not the reason I am here.
I’m wanting to randomly select 5 cards. Let’s say that a randomly selected card is at index 27 of my deck object. I want to then move that card to index 51 and repeat this 4 times. That way the last five cards of my deck object were all randomly selected and it’s impossible for them to be selected twice. I am thinking the easiest approach (which I have not attempted yet) would be to create a variable that holds the value of one of my deck indices so I can swap them around. Would any of you agree?
Any help is greatly appreciated!
You have your
deckas reference of classDeckpointing to an instance: –So, you can’t access it on index like array: –
I think you probably need to give some method in your class like
get(index)and access it like: –deck.get(index)Or may be you wanted to declare your
deckas: –then that (
deck[index])would work.