Reputation: 4180
I'm new to Java, and I'm getting an error in my main function when I try to create an instance of a DeckofCards class. The DeckofCards class is supposed to be a private array of "Cards" objects. I think my issue is something in the DeckofCards class, for some reason it's not an array I think? Maybe I created it wrong?
The errors in my main are '(' or '[' expected and array required but DeckofCards found
Here is my main function:
public static void main(String[] args) {
Card myCard = new Card(13,1);
System.out.println(myCard.getSuit());
System.out.println(myCard);
DeckofCards myDeck = new DeckofCards; //error here
for(int i=0; i<53; i++) {
System.out.println(myDeck[i]); //second error here
}
}
Here is my DeckofCards class:
public class DeckofCards {
private Card[] deck = new Card[52];
public DeckofCards(){
int i = 0;
for(int s = 1; s<5; s++){
for(int r = 1; r<14; r++){
deck[i].rank = r;
deck[i].suit = s;
i++;
}
}
}
}
If anyone can tell me if I'm missing some syntax or something that'd be great! Thank you.
Upvotes: 2
Views: 15084
Reputation: 159754
The error is pretty clear, myDeck
is a single custom Object
rather than an array
DeckofCards myDeck = new DeckofCards(); // parenthesis here
for (int i=0; i<53; i++) {
System.out.println(myDeck); // no brackets here
}
Although the loop itself should be located within the toString
method of the DeckofCards
class.
Upvotes: 3
Reputation: 22553
In order to iterate through the DeckofCards you'll want to expose that private Card[] array. You can use the bean notation getCards() or just make the array public.
public class DeckofCards {
private Card[] deck = new Card[52];
public DeckofCards(){
int i = 0;
for(int s = 1; s<5; s++){
for(int r = 1; r<14; r++){
deck[i].rank = r;
deck[i].suit = s;
i++;
}
}
}
public Card[] getCards(){
return deck;
}
}
I would probably just make the deck public.
Upvotes: 1
Reputation: 2920
Replace
DeckofCards myDeck = new DeckofCards;
with
DeckofCards myDeck = new DeckofCards();
and myDeck
was never initialized to be an array.
Upvotes: 3
Reputation: 234795
You need to call the constructor:
DeckofCards myDeck = new DeckofCards(); // note parens!
In Java, the parentheses are required.
In the constructor, you will also need to initialize each element of the array to a new Card
object:
for(int s = 1; s<5; s++){
for(int r = 1; r<14; r++){
deck[i] = new Card();
deck[i].rank = r;
deck[i].suit = s;
i++;
Upvotes: 5