Shalheira
Shalheira

Reputation: 5

How to read and return the second index of an array if first index matches a string?

I'm trying to write a translate method using the following parameters. However, every time I run the method it skips the first if statement and goes right to the second for loop.

/** Translates a word according to the data in wordList then matches the case. The parameter wordList contains the mappings for the translation. The data is organized in an ArrayList containing String arrays of length 2. The first cell (index 0) contains the word in the original language, called the key, and the second cell (index 1) contains the translation. It is assumed that the items in the wordList are sorted in ascending order according to the keys in the first cell. @param word The word to translate. @param wordList An ArrayList containing the translation mappings. @return The mapping in the wordList with the same case as the original. If no match is found in wordList, it returns a string of Config.LINE_CHAR of the same length as word. */

public static String translate(String word, ArrayList<String[]> wordList) {
    String newWord = "";
    int i = 0;
    for (i = 0; i < wordList.size(); i++) {
        word = matchCase(wordList.get(i)[0], word);  //make cases match
        if (word.equals(wordList.get(i)[0])) {       //check each index at 0
            newWord = wordList.get(i)[1];            //update newWord to skip second for loop
            return wordList.get(i)[1];
        }
    }
    if (newWord == "") {
    for (i = 0; i < word.length(); i++) {
        newWord += Config.LINE_CHAR;
    }
    }

    return newWord;
}

For the files I'm running, each word should have a translated word so no Config.LINE_CHAR should be printed. But this is the only thing that prints. How do I fix this.

Upvotes: 0

Views: 344

Answers (1)

phatfingers
phatfingers

Reputation: 10250

You are initializing newWord to the value "". The only time newWord can possibly change is in the first loop, where it is promptly followed by a return statement, exiting your method. The only way your if statement can be reached is if you didn't return during the first loop, so if it reaches that if statement, then newWord must be unchanged since its initial assignment of "".

Some unrelated advice: You should use the equals operator when comparing strings. For example, if ("".equals(newWord)). Otherwise, you're comparing the memory address of the two String objects rather than their values.

You may need to share your matchCase method to ensure all bugs are addressed, though.

Upvotes: 1

Related Questions