Guess number with Java with while loop and with attempts

1

I have done this program with Java, that the user has to guess the number with 5 attempts, the number is 6, but the second attempt hangs up

import java.util.Scanner;

public class Practica15 {

    public static final int NUMERO_SECRETO = 6;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int num=0;
        int intentos=5;

        Scanner teclado= new Scanner(System.in);

        System.out.println("Introduce un numero");
        num=teclado.nextInt();

        if (num==NUMERO_SECRETO && intentos<=5) {
            System.out.println("El numero es correcto");
        }

        while (num != NUMERO_SECRETO && intentos >= 1) {
            intentos--;
            System.out.println("Error, el numero no es correcto, te quedan: " +
                intentos + " intentos ");
            teclado.nextLine();
            System.out.println("Introduce el numero de nuevo");

            num=teclado.nextInt();

            teclado.close();
            if (num==NUMERO_SECRETO && intentos <5) {
                System.out.println("Correcto. Lo has conseguido en " + 
                    intentos + " intentos");
            }else if (num!=NUMERO_SECRETO && intentos==1) {
                System.out.println("Has agotado los intentos");
            }
        }
    }

}
    
asked by marxal 17.10.2017 в 09:40
source

1 answer

3

The problem you have is that you close the Scanner, deleting the line teclado.close(); should work perfect.

I hope it helps, greetings.

    run:
Introduce un numero
3
Error, el numero no es correcto, te quedan: 4 intentos 
Introduce el numero de nuevo
5
Error, el numero no es correcto, te quedan: 3 intentos 
Introduce el numero de nuevo
6
Correcto. Lo has conseguido en 3 intentos
BUILD SUCCESSFUL (total time: 10 seconds)
    
answered by 17.10.2017 / 10:18
source