Try - Catch and Variable not initialized

8

I just learned the basic structure of the Try-Catch and I made a small code to test it, but it gives me an uninitialized variable error. Can someone instruct me a little about this? I leave the code:

public static void main(String[] args) {
    //Variables
    String nomApel1, nomApel2;
    int edad1, edad2;
    boolean repeat = true;

    while (repeat) {
        //Pidiendo valores de variables al usuario.
        try {
            nomApel1 = JOptionPane.showInputDialog("Nombre y apellido de persona 1: ");
            edad1 = Integer.parseInt(JOptionPane.showInputDialog("Edad de la persona 1: "));
            nomApel2 = JOptionPane.showInputDialog("Nombre y apellido de persona 2: ");
            edad2 = Integer.parseInt(JOptionPane.showInputDialog("Edad de la persona 2: "));
            repeat = false;
        } catch (NumberFormatException ex) {
            System.out.println("Dato inválido, intentalo de nuevo.\n");
        } finally {
            //En todas las variables aquí me dice error de inicialización.
            if (edad1 > edad2) {
                JOptionPane.showMessageDialog(null, "Datos de la persona mayor: \nNombre completo: " + nomApel1 + ".\nEdad: " + edad1 + ".");
            } else {
                JOptionPane.showMessageDialog(null, "Datos de la persona mayor: \nNombre completo: " + nomApel2 + ".\nEdad: " + edad2 + ".");
            }
        }
    }

}
    
asked by Deivis Cervantes Puello 22.03.2018 в 05:45
source

2 answers

8

The error it gives you is because you have to give a value to the variables nomApel1, nomApel2, age1 and age 2.

The explanation is very simple, try catch finally is a structure that serves to control the exceptions that can "jump".

In your code, imagine that it gives an exception when collecting the value of nomApel1 in this instruction:

nomApel1 = JOptionPane.showInputDialog("Nombre y apellido de persona 1: ");

When you give an exception, you will go to the catch area (there you have everything right), but then you will execute the area of the finally and that is where you will have problems because, since you could not have collected the data of age1, age2 ... you will not be able to compare them or show their value.

To avoid this, as your partner @ Dev.Joel has said in your answer, you should give some initial value at both age1 and age2 as well as nomApel1 and nomApel2 which may be like this:

public static void main(String[] args) {
//Variables
String nomApel1 = "";
String nomApel2 = "";
int edad1 = 0;
int edad2 = 0;
boolean repeat = true;

while (repeat) {
    //Pidiendo valores de variables al usuario.
    try {
        nomApel1 = JOptionPane.showInputDialog("Nombre y apellido de persona 1: ");
        edad1 = Integer.parseInt(JOptionPane.showInputDialog("Edad de la persona 1: "));
        nomApel2 = JOptionPane.showInputDialog("Nombre y apellido de persona 2: ");
        edad2 = Integer.parseInt(JOptionPane.showInputDialog("Edad de la persona 2: "));
        repeat = false;
    } catch (NumberFormatException ex) {
        System.out.println("Dato inválido, intentalo de nuevo.\n");
    } finally {
        //En todas las variables aquí me dice error de inicialización.
        if (edad1 > edad2) {
            JOptionPane.showMessageDialog(null, "Datos de la persona mayor: \nNombre completo: " + nomApel1 + ".\nEdad: " + edad1 + ".");
        } else {
            JOptionPane.showMessageDialog(null, "Datos de la persona mayor: \nNombre completo: " + nomApel2 + ".\nEdad: " + edad2 + ".");
        }
    }
}

}

Now the problem is that if you have an exception it will give you the values 0 for the int and "" for the Strings but you will be able to run the program without problems

    
answered by 22.03.2018 / 07:48
source
7

This error is very common, In Java when declaring local variables, that is to say within a method, for example (for its case the main one) no default values are added in its initialization, as it happens when declare a variable at the class level, for this reason you must initialize these variables with some value, you must have three points clear.

int a;  //declaración
a = 2 ;// inicialización
int a = 2; // declaración e inicialización

Then in your example you could initialize 0 , int and null String for example as it does with your Boolean variable and problem solved.

String nomApel1=null; nomApel2 = null;
int edad1=0; edad2 = 0;
    
answered by 22.03.2018 в 06:50