So i am creating a deck constructor for a card game in which the for loop is not working. This is the code for it, and disregard the third integer variable in the constructor for it does not solve the problem and so i commented it out:
public Deck(String[] ranks, String[] suits, int[] values) {
cards = new ArrayList<Card>();
for(int a = 0; a<=ranks.length; a++){
for(int b=0; b<=suits.length;b++){
cards.add(new Card(ranks[a],suits[b], 0));
System.out.println(cards);
size+=1;
}
}
}
My nested for loop is not working, however. I created a suits and ranks array for all the cards in a deck from One to the Ace and the suit array containing "Hearts", "Spades", "Clubs", "Diamonds". Here is the output for the print that i was receiving while troubleshooting and also the error message i am receiving along with it.
[(One of Hearts (point value = 0)][(One of Hearts (point value = 0), (One of Spades (point value = 0)]
[(One of Hearts (point value = 0), (One of Spades (point value = 0), (One of Clubs (point value = 0)]
[(One of Hearts (point value = 0), (One of Spades (point value = 0), (One of Clubs (point value = 0), (One of Diamonds (point value = 0)]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Deck.<init>(Deck.java:36)
at DeckTester.main(DeckTester.java:14)
My understanding was that the nested for loop would finish the Suits array list that contains 4 suits much like it has in the printed output. However, i thought that after it ran through the four times, instead of producing an error, the "a" for loop would then move to the next item in the ranks array instead of ending. So its output in ordered pairs would look like
(0,0) (0,1) (0,2) (0,3) (1,0) (1,1) (1,2) (1,3) etc.
Any help would be greatly appreciated and i thank you for your time.
An array of n elements has indices from 0
to n-1
. n
is an invalid index for such an array.
Your indices are off by one. It should be :
for(int a = 0; a<ranks.length; a++){
for(int b=0; b<suits.length;b++){
cards.add(new Card(ranks[a],suits[b], 0));
System.out.println(cards);
size+=1;
}
}
}