简体   繁体   中英

Searching for a String in an Array and returning the position

Hi I'm a complete newbie on programming and I try to search for a certain String in an array. When it's found the method should return the index but if the String is not found it should return -1.

public int poitionOfWord(String testWord) {
    for (int i = 0; i < wordArray.length; i++) {
        if (wordArray[i].equals(testWord)) {
            return i;
        }
    }
    return -1;
}

would this method return always -1 or would it actually terminate when finding a word and would return i.

Your method is correct and it will return the index in case it finds a match else if it doesn't find the match, it will come out of loop and return -1.

Just to make code crisp and concise, you can use something like this,

public static String[] wordArray = new String[]{"a", "b"};
public static int poitionOfWord(String testWord) {
    return Arrays.asList(wordArray).indexOf(testWord);
}

Then test it with some code,

public static void main(String args[]) {
    System.out.println(poitionOfWord("a"));
    System.out.println(poitionOfWord("z"));
}

This prints,

1
-1

通常,当函数到达return语句时,它将终止并返回给定值。

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