I just learned the basic structure of Try-Catch and made a little code to test it, but it gives me an uninitialized variable error. Can someone educate me a bit 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 + ".");
}
}
}
}
The error it gives you is because you have to give a value to the variables appName1, appName2, age1 and age2.
The explanation is very simple, try catch finally is a structure that is used to control the exceptions that can "jump" you.
In your code, imagine that it throws an exception when fetching the value of nameName1 in this statement:
When throwing an exception, it will go to the catch zone (everything is fine there), but then it will execute the finally zone and that is where it will give you problems since, not being able to collect the age1 data , age2... you will not be able to compare them or show their value.
To avoid this, as the colleague @Dev.Joel has told you in his answer, you should give some initial value both to age1 and age2 and to appName1 and appName2, which can be like this:
Now the problem is that if you have an exception it will give you the values 0 for the int and "" for the String but you will be able to execute the program without problems
This error is very common. In Java, when declaring local variables, that is, within a method, for example (in your case, the main) , default values are not added in its initialization, as happens when a variable is declared at the class level, for such For this reason, you must initialize these variables with some value, you must be clear about three points.
So in your example you could initialize a
0
, losint
and null losString
for example like you do with your boolean variable and problem solved.