简体   繁体   中英

Why doesn't my getIndex method work?

I have written a method named getIndex and it won't return a number when I run the tester.

public int getIndex(String s){
    int index = -1;
    for(int i = 0; (i < names.length && index == 1); i++)
    {
        if(names[i].equals(s)) {
            index = i;
        }        
    }
    return index;
}

In case it's not clear, I'm trying to make the method return which place in the array the given string is located.

EDIT-- [here's my code on ideone] ( http://ideone.com/CM9xID )

Your loop condition is false right away.

You code says:

while 0 < LENGTH_OF_NAMES AND -1 is equal to 1

-1 is never equal to 1 so your loop never happens

Change:

for(int i = 0; (i < names.length && index == 1); i++)

To:

for(int i = 0; i < names.length; i++)

You iterate the wrong way, if comparing for index == 1 the loop never starts as index is declared with -1. if you would declare your index with 1, the loop would start but then run endlessly if names[1] is not equal to s, so just remove it and youre good.

public int getIndex(String s){
    for(int i = 0; (i < names.length; i++)
    {
        if(names[i].equals(s)) { //use equalsIgnoreCase if comparing should be case insensitive
            return i; //found
        }        
    }
    return -1; //not found
}

Another version to do your loop is (if you just want the index you can directly use indexOf() as in the last example shown):

List<String> names2 = new ArrayList<String>(Arrays.asList(names));
for(String name : names2){
    if(name.equals(s))
        return names2.indexOf(name);
}

This is an enhanced for loop .

You can also shortcut and directly get the index:

 List<String> names2 = new ArrayList<String>(Arrays.asList(names));
 return names2.indexOf(s);

Ideone Fiddle

Be aware that you always only get the index of the first occurence. if s is more than once inside the array you must enhance it to store the indexes found and return all of them!

public List<Integer> getIndexes(String s){
    List<Integer> found = new ArrayList<Integer>();
    for(int i = 0; (i < names.length; i++)
    {
        if(names[i].equals(s)) { //use equalsIgnoreCase if comparing should be case insensitive
            found.add(i);
        }        
    }
    return found;
}

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