How to return to main when there is an error?

2

I want that when there is an error for the introduction of user data, I will ask for the data again until they are ok.

public class EntradaDeDatos {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner entrada= new Scanner(System.in);
        int edad=0;

        System.out.println("Introduce tu Nombre, Edad y Fecha de nacimiento");

        String nombre=entrada.next();

        try{
        edad=entrada.nextInt();
        }catch(Exception e)
        {
            System.out.println("Debes de escribir un numero y no una letra ");//////**aqui quiero que regrese a pedirle los datos**
        }

        String fechan=entrada.next();

        System.out.println("Tu nombre:"+nombre+"\n Tu Edad"+edad+"\n Tu Fecha de nacimiento"+fechan);
    
asked by Jaime Saiag 11.09.2016 в 18:32
source

2 answers

3

Use a flag variable datoCorrecto that you initialize to true each time you enter data. Enter the data entry in a do-while loop that repeats as long as% co_of% is false. And if the exception jumps put datoCorrecto to false.

Such that:

int edad=0;
boolean datoCorrecto;
do {
    datoCorrecto = true;  

    System.out.println("Introduce tu Edad");

    try{
        edad=entrada.nextInt();
    }catch(Exception e)
    {
        System.out.println("Debes de escribir un numero y no una letra ");
        datoCorrecto = false;
    }
} while( !datoCorrecto);

The previous code only works for the case of age. Using code similar to the previous one you can solve it for age, name and date.

    
answered by 11.09.2016 / 18:48
source
-1

You can use something like this as well as the following. Try to always use methods and in the main send to call them; each method should have its own error handling logic.

    
answered by 12.09.2016 в 19:34