Reputation: 3
Why does output shows only 13 card but only suit, club. And not the rest of it ? Help anyone ? Is there something wrong with my loop.
public class deck {
public Card[] deck; // field
public deck() {
deck = new Card[52]; // store into deck
}
public void DeckCreation() {
String[] suit = { "Spades", "Hearts", "Diamonds", "Clubs" };//Array for suit
int[] number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; // Array for number
for (int i = 0; i <suit.length ; i++) {
for (int n = 0; n < number.length; n++) {
Card c = new Card(suit[i], number[i]);// Card instantiate
if (deck[i] == null) {
deck[i] = c;
}
}
}
}
public void displayDeck() {
for (int i = 0; i <deck.length; i++) {
if (deck[i] != null) {
deck[i].display(); // display
}
}
}
Upvotes: 0
Views: 40
Reputation: 3729
for (int i = 0; i <suit.length ; i++) {
for (int n = 0; n < number.length; n++) {
Card c = new Card(suit[i], number[i]); // Card instantiate
if (deck[i] == null)
{
deck[i] = c; // Repeatedly trying to access index 0 to suit.length-1
}
}
}
It should be
for (int i = 0; i <suit.length ; i++) {
for (int n = 0; n < number.length; n++) {
Card c = new Card(suit[i], number[n]); // Card instantiate
// Using (i*number.length + n) will get you from index 0 to 51
if (deck[(i*number.length + n)] == null)
{
deck[(i*number.length + n)] = c; // Accessing index 0 to 51
}
}
}
(0 * 13 + 0) = 0, (0 * 13 + 1) = 1, (0 * 13 + 2) = 2..
(3 * 13 + 0) = 39, (3 * 13 + 1) = 40, ..., (3 * 13) + 12 = 51..
Upvotes: 1
Reputation: 70327
Card c = new Card(suit[i], number[i]);// Card instantiate
This should be
Card c = new Card(suit[i], number[n]);// Card instantiate
Upvotes: 0