Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda