Search code examples
stringwhile-loopswitch-statementterminate

How would I get a while loop to terminate when the user inputs "no"


I have this while loop for a Blackjack Class:

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;
  }
}

I want the loop to end when the user inputs a "no" when asked if he would like another card. Currently If i input anything but "yes" it will continue to ask `Would you like another card?'. I understand why this is happening, but I have no idea how to fix it. Thanks in advance.


Solution

  • Add an else to the end of the if-Statement and break out of the loop.

    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;
    }
    

    Note: This will break out of the loop when the user inputs anything different than "yes". If you want to break out only on no, use else if.