how is a data in java valid?

1

For example, I ask for a whole piece of information and when I enter a letter for example, tell me that the data entered is not valid.

I have put this, but it does not work for me

while (teclado.hasNextInt()==false) 

    System.out.println("El caracter introducido no es valido");

    teclado.next();
    
asked by marxal 08.10.2017 в 18:53
source

1 answer

1

Simple, nextInt() can only receive integers, if you pass a letter this will throw an exception. You can handle that exception with try catch within a cycle while , which as long as non-numeric values are entered, continue executing and when a number is entered it stops.

import java.util.Scanner;
import java.io.IOException;
import java.util.InputMismatchException;

public class Numero{

    public static void main(String[] args) {

        Scanner teclado = new Scanner(System.in);
        int numero;
        boolean noEsNumero = true;

        System.out.println("Ingrese el numero");

        // El while evaluá la variable noEsNumero la cual es true por defecto,
        // a esta se le asigna el valor false si el valor ingresado por el 
        // usuario es un numero. Mientras el valor que ingrese el usuario 
        // no sea un numero, el while se ejecutara.
        while (noEsNumero) {

            try {

                // Recibe el valor ingresado por el usuario, si el valor ingresado
                // por el usuario no es un numero, el try se ejecutara hasta
                // esta linea y saltara al catch. Pero si es un numero, el try se
                // ejecutara completo y le asignara a la variable noEsNumero es valor
                // false, lo que detendrá el ciclo. 
                numero = teclado.nextInt();
                noEsNumero = false;

            } catch (InputMismatchException e) {
                System.out.println("Error: no es un numero");
                System.out.println("Intentelo de nuevo");
            }

            // Esta linea es necesaria para el correcto funcionamiento de la entrada.
            // esta linea siempre debe ir después de utiliza el método nextInt(). 
            teclado.nextLine();

        }

        // Cierra el teclado
        teclado.close();

    }

} 
    
answered by 08.10.2017 / 20:59
source