Search code examples
javacharacter-arrays

How to return multiple values


For my program i have to pull a string from a data file and put that string into an array char by char. I have a method that gets a user input and if the word matches any of index it reveals the missing letter. What i'm having trouble is words that have the same letter repeated over, for example my word is "Hello". if i type in the letter 'l' it returns the index as 3. and reveals the second L but not the first. So my question is how can i also get the index 2. Here is the code

public int correctWord (char[] n,String word,char c){
    int index=0;
    for(int i =0; i < word.length();i++){
        if( c == n[i]){
            index = i;
        }            
    }
    return index;
}

Solution

  • You can return an ArrayList of indexes:

    public ArrayList<Integer> correctWord (char[] n,String word,char c){
        ArrayList<Integer> indexes = new ArrayList<Integer>();
        int index=0;
        for(int i =0; i < word.length();i++){
            if( c == n[i]){
                indexes.add(i);
            }            
        }
    
        return indexes;
    }