I am trying to find the index of an array. My array is the following:

char[] closingBrackets = { ')', ']', '}', '>' };

when I do:

int i =  openingBrackets.indexOf(']');

or

int i =  openingBrackets.indexOf(]);

Eclipse gives me an error then recommending that I change it to openingBrackets.length which is not what I want.

I want in this case for i to hold the value 1 since it is the second item in the array. Where am I going wrong? Or is there another library that I should be using to find this?

有帮助吗?

解决方案

indexOf is a method for Strings. To see where the element is at, loop through the array, checking each value to see if it matches, and when you get to it, return the number of the loop tracking in (the int)

int index;
for(int i = 0; i < array.length; i++) {
    if(array[i] == ']') {
        index = i;
    }
}

其他提示

Arrays dont have methods. You could use

int index = Arrays.asList(closingBrackets).indexOf(']');

provided closingBrackets is defined as a Character array

Character[] closingBrackets = { ')', ']', '}', '>' };

First, you can't call indexOf on an array. I think you are getting confused with ArrayList. To find the index of an object in an array, make a method like this: (this would require you to make it an Character[])

public static <E> int indexOf(E[] array, E item) {
    for (int i = 0; i < array.length; i++)
        if(array[i].equals(item))
            return i;
    throw new InvalidParameterException("Item not in array.");
}

Or you could convert the array to an ArrayList<Character> and call the method indexOf(int).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top