简体   繁体   中英

Try Catch With Loop Java

I'm new Java student. Maybe I don't understand how try/catch really works. I'm making a Java class game, the hangman. And I'm making a method that returns the number of players. I have another code that works perfectly. Just if I introduce letters and no Int, it crash. I tried to make this one. I hope you understand me.

public static int setNumJugadores() {
    Scanner sc = new Scanner(System.in);
    int numJugador=0;
    System.out.println("Introduzca el número de jugadores a jugar: ");
    // VARIABLES PARA EL TRY CATCH


    boolean bError=false;
    boolean mayorQueCero=false;
    do {
        try{
            numJugador = sc.nextInt();
        }
        catch (Exception e){
            bError=true;
            System.out.println("Error, introduzca un numero entero.");
        }

        if (numJugador < 1) {
            System.out.println("ERROR, introduzca un valor valido mayor de 0");
        }
        else{
            mayorQueCero=true;
        }
    } while ((!mayorQueCero)||(!bError));

    return numJugador;
}       

The problem is, if someone enters letters, the exception will in fact be thrown, and you will catch it. However those characters are not removed from the input. So the next time you try to read the input, you will still have characters, and the exception will be thrown again.

Add a sc.nextLine(); in the catch block to eat up the bad line of data.

The problem here is

nextInt() : Scans the next token of the input as an int

When you enter character it throws exception and goes to catch block and the program crashes.

Use the following code

public static int setNumJugadores() {
    Scanner sc = new Scanner(System.in);
    String numJugador=null;
    System.out.println("Introduzca el número de jugadores a jugar: ");
    // VARIABLES PARA EL TRY CATCH


    boolean bError=false;
    boolean mayorQueCero=false;
    do {
        try{
            numJugador = sc.nextLine();
        }
        catch (Exception e){
            bError=true;
            numJugador = null;
            System.out.println("Error, introduzca un numero entero.");
        }

        if (numJugador == null) {
            System.out.println("ERROR, introduzca un valor valido mayor de 0");
        }
        else{
            mayorQueCero=true;
        }
    } while ((!mayorQueCero)||(!bError));

    return numJugador;
}      

nextLine() : Advances this scanner past the current line and returns the input that was skipped.

See the Scanner Java Doc for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM