Reputation: 625
I'm having this interesting ArrayIndexOutofBounds
exception.
The code is this:
int m = 0;
while (scan.hasNextInt())
{
intArray[m++] = scan.NextInt();
}
I'm merely scanning a bunch of integers into an array, but I always get an ArrayIndexOutofBounds
error. I thought my int m
was already initialized to zero?
Thanks
Upvotes: 0
Views: 3063
Reputation: 1724
ArrayIndexOutofBounds means your array isn't big enough to hold the number of values you are putting in it. Where are you initializing the array intArray?
If you don't know how many values the scanner has upfront, which I would assume to be the case, you might want to use an ArrayList instead.
Something like this should work..
List<Integer> intArray = new ArrayList<Integer>();
while (scan.hasNextInt())
{
intArray.add(scan.NextInt());
}
If you need the final results in an array rather then an ArrayLIst, you can use
Integer[] newArray = (Integer[])intArray.toArray();
Upvotes: 0
Reputation: 3322
inputString.length()
returns the number of characters in the string. it does not necessarily correspond to the number of numbers in your string.You will want to add another condition to your while
statement to ensure that m
doesn't get larger than intArray.length
. Also you probably want to step through the code with a debugger to determine exactly when the array runs out of space.
Since java arrays are fixed size, if you don't know what the size of your input is going to be, you should instead use ArrayList<Integer>
to store your input.
Upvotes: 4
Reputation: 6743
Does the array have any elements in it to start off with?
On future iterations of the loop, m is not zero because you increment it inside the loop.
Upvotes: 0