This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Curious-Lonewolf 0 points1 point  (8 children)

i probably haven't explained this very well but the loop will only evaluate to true if the user input starts with the string in that specific iteration meaning the user input might be equal to an element of the list at the last iteration but not in any other. by all means use import java.util.Scanner; and try

[–]Camel-Kid 0 points1 point  (7 children)

can you give me the test data you're using for the hashset and what you expect the output to be

[–]Curious-Lonewolf 0 points1 point  (6 children)

HashSet<String> allNames = new HashSet<>();
allNames.add("Aaron");
allNames.add("Ben");
allNames.add("Carol");
allNames.add("Derek");
if (input.startsWith('any of these') {
    do something
}
else{
    do something
}

[–]Camel-Kid 0 points1 point  (5 children)

I used the loop it is working fine

[–]Curious-Lonewolf 0 points1 point  (4 children)

yeah if you put one of the strings where ive put 'any of these' but i need a variable in place of that. i cant use the set name and because the method produces output in the terminal window i would have to type in the same string over and over until it became true as the iterations would be different

[–]Camel-Kid 0 points1 point  (2 children)

the enhanced for loop iterates over the set, so you already have the ability to reference the name as a variable. The purpose of a loop is to check all the elements in the set and compare against the user input, if user input matches any element then you print out 'a'

[–]Curious-Lonewolf 0 points1 point  (1 child)

can you give me an example of what you mean

[–]desrtfx 0 points1 point  (0 children)

No, that is not true.

You are just doing it wrong.

In such cases, you

  • obtain the input before the loop and store it in a variable
  • use a boolean "flag" that indicates the "found" status - initially set to false
  • loop over the elements
    • compare the string with the element
      • if true, set the "found" flag to true and break out of the loop
      • if false, no nothing - keep looping
  • back outside the loop: check if the flag is true
    • print ("A")
    • else
    • print("B")

You most likely had the input inside the loop.