4 votes

I do not understand why java shows me the message of this code

My problem is very simple, it turns out that when I ask a parameter to the user ,the Java me run a If you should not run, look, I show you the code snippet:

public static void main(String[] args) {

    int op=0;  
    String dato; 
    do{ 

        try{ 
            dato=JOptionPane.showInputDialog("Seleccionar una operacion:\n "
         + "1.- Suma\n"
         + "2.- Limite\n"
         + "3.- Resta\n"
         + "4.- multiplicacion\n"
         + "5.- Salir"       
            );  
            op=Integer.parseInt(dato);

        }
        catch(NumberFormatException ex){ 
            JOptionPane.showMessageDialog(null,"Ingresar una opcion entre 1 y 5"); 
        }

        if(op<=0){
            JOptionPane.showMessageDialog(null,"Ingrese valores positivos entre 1 y 5");
    }  

Ok, now suppose that we ask a number to the user, and the user entered this "AJHKHDAS", then the try - catch would do its work, and Java should only show this message:

catch(NumberFormatException ex){ 
     JOptionPane.showMessageDialog(null,"Ingresar una opcion entre 1 y 5"); 
}  

Here is where comes the problem for some strange reason, after displaying the first message, which in theory is correct, it shows me the message from the if that follows him, that would be this:

 if(op<=0){
     JOptionPane.showMessageDialog(null,"Ingrese valores positivos entre 1 y 5");
 } 

and I don't understand why it does, since at no time entered a number less than or equal to zero, that is my only doubt, the user when inputting characters I should show the if that comes below.

4voto

Daniel Faro Points 808

At the beginning of the program you are giving OP the value 0. When the exception is skipped, no new value is given to OP, therefore when it reaches the IF, as OP it is still worth 0 enters.

2voto

Alberto Méndez Points 344

Notice that you are initializing the variable "op" to 0, so when entering the try catch as it jumps to the error, the variable "op" does not change its state, consequently "op" is still 0 and when it reaches that "if" "the condition is correct

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X