0

I am trying to make a method that takes in an ArrayList and a letter. If the words in the arraylist start with that letter, than it will be put into a new array of words that start with that letter. For example, an arraylist with ("Apple", "Anny", "Bob") and a letter of "A" would create a new arraylist ("Apple", "Anny"). I am not allowed to use .startsWith(char ch)

public ArrayList<String> wordsThatStartWith(ArrayList<String> words, String letter)
{
    ArrayList<String> newWords = new ArrayList<String>();
    for(int i = 0; i < words.size(); i++){
        if((words.get(i)).substring(i, i + 1) == letter){
        newWords.add(words.get(i));
    }
}
return newWords;
}

I am not sure why it will not add into a new ArrayList.

1 Answers1

0

Replace

if((words.get(i)).substring(i, i + 1) == letter)

with

if((words.get(i)).substring(0, 1).equalsIgnoreCase(letter))

as you need to get just the first character from the string.

Using the enhanced for loop, you can write it as

for(String word: words) {
    if(word.substring(0, 1).equalsIgnoreCase(letter)){
        newWords.add(word);
    }   
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110