Reputation: 9
I'm making a program of the Card game War and I need the cards to not reappear so I used an Array list. I'm having trouble with this array list as it's supposed to be random and remove the number, but I get the error IndexOutOfBoundsException: Index 0, Size 0
List<Integer> values = new ArrayList<Integer>();
Random random = new Random();
Integer rand = random.nextInt(values.size()+1);
Integer cardId = values.get(rand);
values.remove(rand);
Upvotes: 0
Views: 2609
Reputation: 208974
You need to first give the List values before you can get
values
List<Integer> values = new ArrayList<Integer>();
Random random = new Random();
Integer rand = random.nextInt(values.size()+1);
Try this to put values
for (int i = 1; i <= 52; i++){
values.add(i);
}
Integer rand = random.nextInt(values.size() + 1);
Upvotes: 0
Reputation: 201439
First add your Card(s) to your values List (e.g. probably not Integer). What I'm saying is this, you need a deck of cards before you can play.
Upvotes: 3
Reputation: 40315
You get this error because you try to access index 0 of an empty array, as it says. You cannot do this.
Your code has multiple issues.
You are not actually storing anything in values
.
The acceptable range of indexes for .get()
is 0 to size-1. The return range of random.nextInt(size+1)
is 0 to size. This can produce out of range index values. Array indexes start at 0.
Upvotes: 2
Reputation: 135
Provide the code for the values in the array...Or add values in the array.
Upvotes: 0
Reputation: 44439
Your list is empty and you're
1) Trying to retrieve a value
2) Trying to remove a value
Which throws an error because the list is empty.
Sidenote: you can define rand
and cardId
as int
, instead of Integer
. Autoboxing/unboxing will take care of that for you.
Add values to your list and it will work as expected (and if you change random.nextInt(values.size()+1)
to random.nextInt(values.size())
).
Upvotes: 2