First of all, if is not a loop. So there is no point in labelling it so as use a labelled break.
Secondly, both of your code isn't really doing, what you said you want to do. Also, I don't understand why are you doing if (w.equals(s)) this test. And what is w used for.
You said: - w being the word to add, but again you are saying that, you will add the words from your string after splitting it on "\n", if it is not already in your array. So, you are adding many words, not just one word. Please re-read your post, and edit it if necessary.
As per your current problem statement, I would approach it like this: -
- First split your lines on
"\n" to get an array with individual words.
- I would rather use
StringBuilder or StringBuffer if I want to modify my string on each iteration.
- Now, on each iteration, check whether your
StringBuilder already contains that word. If it does not contains, then append it, else leave it.
- At the end of your loop, print your
StringBuilder instance.
Or, as you are saying, you can also use an ArrayList to store your words. Or if, you want unique words only, you should rather use a Set instead. That would not require you to do the test. It handles the duplicates on its own: -
List<String> wordList = new ArrayList<String>();
Set<String> set = new LinkedHashSet<String>();
for (String s : words.split("\n")) {
if (s.contains("" + letter)) {
if (!wordList.contains(s)) {
wordList.add(s); // Add to list.
}
set.add(s); // Add to set.
}
}
And then print your ArrayList or Set by iterating over either of them.
asdf\nasdf\nasf, for this string, your code will fail, ifwis a single character. But what you have stated, from that, I would add all the 3 words to the new string.if (w.contains("" + letter)). I apologize for clarity.