-1

My while loop runs fine and the sentinel (String End) value ends the loop...the issue is that the when the sentinel is entered, the else println statement occurs.

I want the sentinel value to end the loop and not have the final else statement occur

while (!nameSearch.equalsIgnoreCase(sentinel)) {

      showMenu();
      nameSearch = keyboard.nextLine();

      if (girlList.contains(nameSearch.toLowerCase()) && 
         boyList.contains(nameSearch.toLowerCase())) {
         System.out.println("Name found in both boy and girl names\n");
       } else if (boyList.contains(nameSearch.toLowerCase())) {
            System.out.println("Boy name found");
       } else if (girlList.contains(nameSearch.toLowerCase())) {
             System.out.println("Girl name found");
       } else {
             System.out.println("Name not found");
       }
}

System.out.println("program end");
Ivar
  • 6,138
  • 12
  • 49
  • 61
Rye Guy
  • 45
  • 2
  • Swap the order of operations, assign at the end of the loop. – Boris the Spider Apr 15 '18 at 16:28
  • [What does your step debugger tell you?](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) –  Apr 15 '18 at 17:42

2 Answers2

0

There are a few ways to achieve what you want. One method would be to check if the sentinel value was entered, and break out of the loop immediately if it was:

if ((nameSearch = keyboard.nextLine()).equalsIgnoreCase(sentinel)) {
    break;
}
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
-1

just break the loop once value equal to sentinel value

showMenu();
      nameSearch = keyboard.nextLine();
      if(namesearch.equals("sentinelvalue"))//replace your sentinel value
          break;

If case not matter for sentinel value then can use

if(namesearch.equalsIgnoreCase("sentinelvalue"))//replace your sentinel value
              break;
Roushan
  • 4,074
  • 3
  • 21
  • 38