当用户输入" no"时,如何让while循环终止?

时间:2015-09-27 20:41:33

标签: string while-loop switch-statement terminate

我有一个二十一点类的循环:

while (playerSum < 21) {
  System.out.println("Would you like another card?");
  String input;
  System.out.flush();
  input = in.readLine();
  if (input.equalsIgnoreCase("yes")){
    int card3;
    Random r3 = new Random();
    card3 = r3.nextInt(11 - 2 + 1) + 2;
    switch (card3) {
      case 2: System.out.println("You were dealt a Two"); break;
      case 3: System.out.println("You were dealt a Three"); break;
      case 4: System.out.println("You were dealt a Four"); break;
      case 5: System.out.println("You were dealt a Five"); break;
      case 6: System.out.println("You were dealt a Six"); break;
      case 7: System.out.println("You were dealt a Seven"); break;
      case 8: System.out.println("You were dealt a Eight"); break;
      case 9: System.out.println("You were dealt a Nine"); break;
      case 10: System.out.println("You were dealt a Ten"); break;
      case 11: System.out.println("You were dealt a Ace"); break;
    }
    playerSum += card3;
  }
}

我希望在用户输入&#34; no&#34;当被问到他是否想要另一张卡时。目前如果我输入任何东西,但是&#34;是&#34;它会继续问你想要另一张卡吗?&#39;。我理解为什么会这样,但我不知道如何解决它。提前谢谢。

2 个答案:

答案 0 :(得分:1)

你可以通过添加

来解决这个问题
break;

所以它看起来像

if (no) { break;} 

希望这会有所帮助。

答案 1 :(得分:1)

在if语句的末尾添加一个else并退出循环。

if (input.equalsIgnoreCase("yes")){
    int card3;
    Random r3 = new Random();
    card3 = r3.nextInt(11 - 2 + 1) + 2;
    switch (card3) {
      case 2: System.out.println("You were dealt a Two"); break;
      case 3: System.out.println("You were dealt a Three"); break;
      case 4: System.out.println("You were dealt a Four"); break;
      case 5: System.out.println("You were dealt a Five"); break;
      case 6: System.out.println("You were dealt a Six"); break;
      case 7: System.out.println("You were dealt a Seven"); break;
      case 8: System.out.println("You were dealt a Eight"); break;
      case 9: System.out.println("You were dealt a Nine"); break;
      case 10: System.out.println("You were dealt a Ten"); break;
      case 11: System.out.println("You were dealt a Ace"); break;
    }
    playerSum += card3;
  } else {
break;
}

注意:当用户输入的内容与&#34;是&#34;不同时,这将突破循环。如果您想在no上突破 ,请使用else if