I’m making a card game and I’m getting the error that n must be positive. I did some research and it means that (cards.size) is equal or less than 0 I believe, but I don’t understand how to make my code work, something must be wrong.
Code:
public class Deck
{
public ArrayList <Card> cards;
Deck()
{
cards = new ArrayList<>();
for (int a = 0; a < 52; a++)
{
cards.add(new Card(a));
}
}
public Card PlayerCardDraw ()
{
Random generator = new Random ();
int index = generator.nextInt (cards.size ());
return cards.remove (index);
}
How can I fix my array list so i don’t get this error? it relates back to Card so I’ll post that code too, I know something isn’t right in my Card class but I don’t know if that’s the problem or not.
public class Card
{
int c = 52;
int cardpath[] = new int[c];
Card ()
{
}
public Card(int c)
{
this.c = c;
}
public int getCardPath()
{
return cardpath[c];
}
}
Error message:
java.util.Random.nextInt(Unknown Source) at Cards.Deck.PlayerCardDraw(Deck.java:21)
line 21 is int index = generator.nextInt (cards.size ());
EDIT: I did what Nankumar Tekale said and it’s saying what you guys predicted: It’s drawing more than 52 cards. What I don’t understand is the error is popping up at
for (int i = 0 ; i < 4 ; i++)
{
C = deck.P1CardDraw ();
card [cardNum].draw (i*75+100, 400); //Error line
cardNum++;
}
my P1CardDraw() class
public ArrayList < Card > p1Hand;
public ArrayList < Card > P1CardDraw ()
{
p1Hand = new ArrayList < > ();
p1Hand.add (PlayerCardDraw ());
return p1Hand;
}
Well looking at your
Deckclass, You have intializedcardsin constructor so there should not be such an exception(as cards size is 52).But one thing is possible to get an exception which is
cards is declared publicandyou may have modified it outside class directly. So arraylistcardsis of size 0 and you get IllegalArgumentException exception for your methodRandom.nextInt(int).Make
cardsprivate.If you have withdrawn all cards then size of arraylist would become 0, which may cause an exception. Add check for 0 as :