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

342
Vistas
Java scanner - allowing a certain number of ints

Really struggling to find the answer to this.

I'm creating a game where it asks how many players there are and the max number of players the user can enter is 3 (either 1, 2 or 3). Is this creating a for loop or can I just enter a parameter in the scanner function?

Code below:

System.out.println(" How many players are there? ");

int numberOfPlayers = scan.nextInt();

Player[] players = new Player[numberOfPlayers]; //this is where the players scores are stored
int currentPlayer = 0;  //because arrays start at 0: +1 is added

for (int i = 0; i < numberOfPlayers; i++) {

    System.out.println("What is player " + (i + 1) + " called?");
    String playerName = scan.next();
    players[i] = new Player(playerName);
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You can use Scanner's nextLine() which reads the newline instead of next() as shown below:

    System.out.println(" How many players are there? ");
    int numberOfPlayers = Integer.parseInt(scan.nextLine());
    Player[] players = new Player[numberOfPlayers];
    for (int i = 0; i < numberOfPlayers; i++) {
        System.out.println("What is player " + (i + 1) + " called?");
        String playerName = scan.nextLine();
        players[i] = new Player(playerName);
    }
over 4 years ago · Santiago Trujillo Denunciar

0

I suggest to use Integer.parseInt(scan.nextLine()) with a loop for example :

int numberOfPlayers = 0;
boolean correct = false;
do {
    try {
        System.out.println(" How many players are there? ");
        numberOfPlayers = Integer.parseInt(scan.nextLine());
        if (numberOfPlayers >= 1 && numberOfPlayers <= 3) {
            correct = true;
        }
    } catch (NumberFormatException e) {
    }
} while (!correct);

So if the user enter incorrect number or a number > 3 or < 1 it will ask the user to enter the number again until the the user enter the correct number 1,2,3

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