简体   繁体   中英

array index out of bounds exception in a while loop

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

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.

  1. Does the array have any elements in it to start off with?

  2. On future iterations of the loop, m is not zero because you increment it inside the loop.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM