Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
How to Loop To Get Input Again - Java

I'm creating a game of Twenty One and I'm stuck on how to implement the loops. What I want to do is introduce the game ("Welcome to 21!"), ask the player to roll the dice by typing y, and give them the values of their dice rolls. Then, I want to loop back and ask them to roll the dice a second time by asking them to type y. If they don't type 'y', I want a message to appear telling them they have to type y to play the game. Basically, they will continue being asked if they want to play until they press y.

This is my code thus far. The problem I'm having is if the user presses 'm' instead of 'y', it will tell them "enter y to play the game", but if the user presses y after that, it will keep telling them they have to press y (even though they already did this second time).

 import java.util.Scanner;
 import java.util.Random;

 public class TwentyOne {

 public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Welcome to 21!");

    System.out.print("Roll the dice, y/n?: ");
    String roll1 = input.nextLine();

        while (true) {
            if(roll1.equals("Y") || roll1.equals("y")) {
                int die1 = (int) (Math.random() * 6) + 1;
                int die2 = (int) (Math.random() * 6) + 1;
                int sum1 = die1 + die2;

        System.out.println("Your dice rolled a sum of: " + sum1);
            break;
         } 
        else {
    System.out.println("Please press 'y' to roll the dice and play. ");
              String rollError = input.nextLine();
        }


} 
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You have assign the second input to rollError String rollError = input.nextLine(); and you not using it to check the new user input if(roll1.equals("Y") || roll1.equals("y")). Change String rollError = input.nextLine(); to roll1 = input.nextLine();

over 4 years ago · Santiago Trujillo Relatório

0

This one here will infinitely prompt the user for new rolls (all triggered by pressing the "y", notice the equalsIgnoreCase() too) since that is your described need. But if you ever need a game which ends, don't forget to close (input.close()) the Scanner object to prevent leaks.

    Scanner input = new Scanner(System.in);
    System.out.println("Welcome to 21!");
    boolean isYPressed = false;
    String roll1 = "";

    while (true) {
        System.out.print("Roll the dice, y/n?: ");
        roll1 = input.nextLine();
        isYPressed = roll1.equalsIgnoreCase("y");

        while (!isYPressed) {
            System.out.println("Please press the Y key");
            roll1 = input.nextLine();
            isYPressed = roll1.equalsIgnoreCase("y");
        }

        int die1 = (int) (Math.random() * 6) + 1;
        int die2 = (int) (Math.random() * 6) + 1;
        int sum1 = die1 + die2;

        System.out.println("Your dice rolled a sum of: " + sum1);
    }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda