Java while循环哨兵问题

时间:2018-04-15 16:22:27

标签: java if-statement while-loop sentinel

我的while循环运行良好,并且sentinel(String End)值结束循环...问题是当输入sentinel时,会发生else println语句。

我希望sentinel值结束循环,而不是发生最后的else语句

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");

2 个答案:

答案 0 :(得分:0)

有几种方法可以达到你想要的效果。一种方法是检查是否输入了标记值,如果是,则立即退出循环:

if ((nameSearch = keyboard.nextLine()).equalsIgnoreCase(sentinel)) {
    break;
}

答案 1 :(得分:-1)

一旦值等于标记值

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

如果哨兵价值无关紧要,可以使用

if(namesearch.equalsIgnoreCase("sentinelvalue"))//replace your sentinel value
              break;