Chris Nunes
Chris Nunes

Reputation: 3

ArrayList is not being populated

I'm a bit of a Java noob, so any help is appreciated. I have a method that is supposed to take a char value and an Arraylist of words in alphabetical order, and return all of the strings in the list that start with the same letter as the char. I'm not getting any error messages, but my method keeps returning an empty ArrayList. Why isn't my List being filled?

 public String singlePhrase(char c, ArrayList<String> wordList){

  ArrayList<String> words = new ArrayList<String>();      
  for (int i = 0; i < wordList.size(); i++) { 
     if (wordList.get(i).charAt(0) == c){
        words.add(wordList.get(i));
     }
  }

  return "Size: "+words.size() + " "+c;             
}

Upvotes: 0

Views: 164

Answers (2)

spencer.sm
spencer.sm

Reputation: 20524

If you wanted to return an ArrayList of words use the following:

public ArrayList<String> singlePhrase(char c, ArrayList<String> wordList) {
    ArrayList<String> words = new ArrayList<String>();
    for (int i = 0; i < wordList.size(); i++) {
        if (Character.toLowerCase(wordList.get(i).charAt(0)) == Character.toLowerCase(c)) {
            words.add(wordList.get(i));
        }
    }
    return words;
}

Note that it compares the lowercase version of both characters.

Upvotes: 1

Chris Nunes
Chris Nunes

Reputation: 3

Thank you guys for all the help, but the answer was way too simple. In the .txt file that was being parsed, all the strings began with uppercase letters. The test input was all lowercase, resulting in the '==' being false and the if() statement never being triggered.

Upvotes: 0

Related Questions