Reputation: 47
I'm trying to get this to return a certain number of array entries based on their containing a certain input string.
/**
* This method returns a list of all words from
* the dictionary that include the given substring.
*/
public ArrayList<String> wordsContaining(String text)
{
ArrayList<String> contentCheck = new ArrayList<String>();
for(int index = 0; index < words.size(); index++)
{
if(words.contains(text))
{
contentCheck.add(words.get(index));
}
}
return contentCheck;
}
I don't understand why this keeps returning freaking every value in the array instead of only the entries containing the string bit. Thanks!
Upvotes: 0
Views: 406
Reputation: 30875
You have 2 issues in your code
The first one is one is that You check in your condition
if(words.contains(text))
- this check that text
is in list
and what you probably want is to check that given item of list contains text
public List<String> wordsContaining(String text)
{
List<String> contentCheck = new ArrayList<String>();
for(String word : words) //For each word in words
{
if(word.contains(text)) // Check that word contains text
{
contentCheck.add(word);
}
}
return contentCheck;
}
Upvotes: 1
Reputation: 213401
Your condition:
if(words.contains(text))
checks whether the text
is in the list or not. That would be true
for all or none of the elements.
What you want is:
if(words.get(index).contains(text))
Apart from that, it would be better if you use enhanced for statement:
for (String word: words) {
if(word.contains(text)) {
contentCheck.add(word);
}
}
Upvotes: 3