View Full Version : Exception Handling - Need Help

04-29-2012, 09:40 PM
I'm making a game in Java. I made a new class, and whenever I making an array with it, such as

private Player players[];

the compiler doesn't generate any errors, but when I run it, there is an ArrayIndexOutOfBoundsException thrown. I couldn't figure out how to solve this problem. Any help?

04-30-2012, 04:35 AM
That simply says that players will be an array of Player. It doesn't specify how large that array will be, so by default its of size 0. Before trying to read or write to the array you must specify the size of it:

players = new Player[5];

For example. Arrays do not allow you to resize them; this process must be done manually. If you want to be able to dynamically manipulate the array without too much overhead, look at using collections instead. ArrayList, Vector and LinkedLists are all good alternatives depending on what you want to do with them. Each one has a specific purpose for which they shine, but typically speaking the ArrayList and Vector will be the two most interested in. LinkedList is actually wonderful for creating a cyclic queue btw, so if players are round robin in actions, a LinkedList may be a perfect choice (also look at the queue / stacks [actually I'm not 100% sure java has a queue class - there is a priority queue, but that's not quite the same. I'm quite sure it has a stack]).

04-30-2012, 11:23 PM
I already specified the size to 5(not forgetting the 0 subscript)

players = new Player[5];

then I did

for (int i = 0; i < 5; i++)
players[i] = new Player(150, 150, 20, 20);

but when I run the game, it still throws the ArrayIndexOutOfBoundsException. Any more information?

05-01-2012, 04:32 PM
This above looks fine to me. Post the code you have in use, you are stepping out of bounds elsewhere.

05-02-2012, 03:12 AM
Actually, I just figured the solution to the problem. Sorry for wasting your time.