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

340
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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