Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures Exploring the Java Collection Framework Using ArrayLists

Dylan Carter
Dylan Carter
4,780 Points

Would this work instead?

we changed up the methods for getting hash tags and at signs(I don't use twitter I forgot the name that's given to using them) to have a private method that we then pass into two separate methods to "clean up" the code. I was just wondering if the way I wrote the code would also work for our purpose, I used two for loops instead, please give me any thoughts on this thanks.

public List<String> getPrefixes() {
  List<String> results = ArrayList<String>();
    for (String word : getWords()) {
      if (word.startsWith("#")) {
        results.add(word);
      }
    }
     for (String word : getWords()) {
      if (word.startsWith("'@")) {
        results.add(word);
      }
    }
  return results;
  }

My only thought would be that the variable 'word' might have to be different in each of the loops. or since they are two separate loops can they both have the same variable name?

1 Answer

Hi Dylan,

You can use the word variable twice as each only has scope within the for loop. As soon as that loop exists, word has no further context. That is the reason you have to redeclare it as a String in the second loop.

As for the code, could you not chain an or condition into your if statement to test if the word starts with "@" or "#". That way, we're only looping through the sentence once. Something like:

if (word.startsWith("#") || word.startsWith("@")) { ...

Steve.