Validate Data Obtained by the user with do while

0

Good afternoon! After looking and asking for opinions I have obtained the two ways you can. It only works, if the user inserts a number . Highlight, if you insert letter / character IT DOES NOT WORK .

    short n;
    do {
        System.out.println("Escribir un número entre 11 i 90");
        n = ss.nextShort();
        if (n >= 10 && n <= 90) {
            break;
        } else {
            System.out.println("Valor introducido incorrecto");
            System.out.println("Vuelva introducir nu número");
        }
    } while (true);

In this case you can customize tell the user if the number is not between 10 and 90 , customize the message "return" (else), with "Value entered incorrect".

  

Note: I use "short" and not int, because the user asks me for a 16bit number.

The following is more " short ", but it does not let you customize the message if it is a else . It just says "Write 10 and 90", but it works.

  short n;
    do{
        Scanner ss = new Scanner(System.in);
        System.out.println("Escribe 10 i 90");
        n = ss.nextShort();
        System.out.println("tu número es:" +n);

    }while (n < 10 || n >90);
    
asked by Bob 12.12.2017 в 20:40
source

1 answer

1

My proposal is as follows. When entering the string requested by keyboard, with the regular expression [0-9] (valid for a number), check if the string is valid or not. If it is valid, convert the string to integer and show it by console, on the contrary, it shows error and the variable that controls the while is assigned to false . Thus, as long as correcto is false , the do-while will be repeated.

    Scanner sn= new Scanner(System.in);

    boolean correcto = false;

    do{

    System.out.println("Escribe un número");
    String num= sn.nextLine();

    if (num.matches("[0-9]")) {
        correcto=true;
        int numero = Integer.parseInt(num);
        System.out.println("El número introducido es " + numero);
    } else {
        correcto=false;
        System.out.println("Repite de nuevo");
    }

    }while(correcto==false);
    
answered by 12.12.2017 в 21:12