0

I've been getting this exception and I've no idea how to go about fixing it:

java.lang.ArrayIndexOutOfBoundsException: 3

in the while loop. Here's my code:

public class NameSearch {
    static String[] names = new String[3];

    void populateStringArray() {
        names[0] = "Ben";
        names[1] = "Thor";
        names[2] = "Zoe";
        names[3] = "Kate";
    }

    public static void main(String[] args) {
        String pName;
        int max = 4;
        int current = 1;
        boolean found = false;

        Scanner scan = new Scanner(System.in);
        System.out.println("What player are you looking for?");
        pName = scan.next();
        while (found == false && current <= max) {
            if (names[current] == pName) {
                found = true;
            } else {
                current = current + 1;
            }
        }
        if (found == true) {
            System.out.println("Yes, they have a top score");
        } else {
            System.out.println("No, they do not have a top score");
        }
    }
}

The code is meant to ask the user to input a name and it will check to see if the name is in the array (in a nutshell).

My IDE (Eclipse) says that the error lies in the line if (names[current] == pName){.

1

5 Answers 5

2

The problem lies within this condition: found == false && current<= max - Sidenote: found == false can be simplified to !false and will still evaluate to the same result. current<=max allows the loop to run with current == max and max is defined as 4. Thus you get a read at names[4] which is out-of-bounds. The simplest solution would be to change the condition from current <= max to current<max. And current is initialized as 1. Since arrays are 0-based in java this will cause the program to ommit the first name, which is at names[0].

And another sidenote: using a constant as max is an extremely bug-prone method. Initialize max with names.length instead.

2

Your while loop needs fixing: When your current is equal to max, it will still check for name[4] which doesnot exist.

In Addition, == is not the best way to compare 2 Strings. You must use .equals() method as it compares value of 2 String instead of comparing 2 Object reference. This is how your while loop should be fixed:

while (found == false && current< max){

    if (names[current].equals(pName)){
        found = true;
    } else {
        current = current + 1;
    }
}
2

Here:

static String[] names = new String[3];

You are initializing an array with a capacity of three items, not a maximum index of 3. To get an array with 0, 1, 2, and 3, that's four items, so you'll need to initialize the array like so:

static String[] names = new String[4]; // (0-3)

Also, loops and arrays are zero-based, so you'll want to start with a current of 0 rather than 1 to loop over your array.
Additionally and finally, you'll want to switch the <= to < in your while loop, since we want it to only go up to 3.

2

It's because you have the condition current <= max. If max is 4 then that means current can equal 4 and there is no index 4 in the array. That's why the error comes from names[current], you are trying to access index 4 and it doesn't exist. You should just use < instead of <= or have max = 3 instead of 4.

Side Notes:

  • Because arrays start with an index 0 if current equals 1 when the loop begins it will never look at the first index in the array.
  • When checking the value of a boolean as a condition, instead of doing == true or == false, you can just put the variable for true or add a ! before for false. So in this case instead of while(found == false you can do while(!found.
  • When incrementing an int, instead of current = current + 1, the common practice is to use current++ when incrementing by 1 or += when incrementing by more than 1 (for example current +=2 would increment current by 2).
2

You are indexing your array elements in the loop between 1 and 4 (inclusive), when you need to be indexing them between 0 and 3 (inclusive).

Change current to start at 0, and max to be 3 and you should be all good.

For perhaps an even better alternative, consider putting your list of names in a HashSet and not needing to iterate at all. E.g.

Set<String> names = new HashSet<String>();
names.add("Ben");
names.add("Thor");
names.add("Zoe");
names.add("Kate");

if (names.contains(pName)) {
//...

If the ordering of the names is important, then you could use a List instead, which also has a contains method (just not generally as efficient as that in a Map implementation.. O(n) vs O(1) typically). If the number of names in your list is small, or performance is not an issue, then it will not matter either way.

4
  • You might want to fix your code example ... ;P (it can't compile in the current state)
    – Tom
    Commented Sep 9, 2015 at 16:41
  • @Tom You mean because it refers to pName or because the if is not completed? The intention was not for the code to compile on its own, just to be a short snippet to illustrate what changes to make to the original code to use a better solution than loop iteration for checking the player name. Commented Sep 9, 2015 at 19:46
  • No, I meant the everyone uses " for String literals (and ' for chars), so you should do that, too ;P.
    – Tom
    Commented Sep 9, 2015 at 20:03
  • 1
    @Tom lol, good point, will fix it, thanks! I have been writing too much JavaScript lately and our style guide for JS demands single quotes for strings (to my everlasting frustration). Commented Sep 9, 2015 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.