I am trying to get this method to which I introduce a message as a parameter to return a positive integer, I also have to use a try-catch so that it asks me until I insert a correct value. It gives me an error when putting the return inside the try.
public static int enteroPositivo(String mensaje){
int entero = 0;
do{
try{
System.out.println(mensaje);
Scanner scan = new Scanner(System.in);
entero = scan.nextInt();
return entero;
} catch (Exception e){
System.out.println("Por favor, introduzca un valor correcto.");
}
}while (entero>0);
}
Since your method returns an integer, you can't leave the
return
only inside thetry/catch
Suppose you have the following function
And then we enter do the following.
You may notice that your function
dividir
is not going to stop the program even if it fails, that's what thetry/catch
. However, when using it and assigning it to aint
uni, it will not be assignedint
because it never reached areturn
In short you can't say that your function will return a
int
because you are lying, you could see in the previous example that it doesn't always return it.Speaking of your particular example now, it's clear that you force your program to return a
int
because you don't exit the loop until it does. but for the compiler it is still mandatory that your function yes or yes, return aint
Therefore it suffices to return an
int
out of thetry/catch
You can read this article if you have any doubts.