If statement not comparing JInputDialog value

392 Views Asked by At

So I have an If Statement. It's set to compare a value taken fron user input using JOptionPane.showInputDialog. But if the values are the same, it doesn't do anything...

Example: The user has to enter the value 4. When the Input Dialog appears, the user types 4. Then, it's supposed to win, because if userInput = 4 {win}. But even if the userInput is 4, nothing will happen...

I thik I'm not explaining very well...

EDIT: Ok, I found the problem... I'm stupid... The problem was I declared another int for the num inside the method, so it wasn't reachable outside the method...

2

There are 2 best solutions below

0
On

Ok, I found the problem... I'm stupid... The problem was I declared another int for the num inside the method, so it wasn't reachable outside the method...

2
On

It's important to remember that the input dialog takes strings so the number that you enter will actually be stored in memory as a String object.

int intInput = Integer.parseInt(stringInput);

That will parse the user's input and store as an integer. It's probably best to check that it's possible to parse the input before actually parsing so that the program doesn't crash/bug out.

EDIT: You could also do this:

    if(userInput.equals("4")) { 
      JOptionPane.showMessageDialog(null, "win"); 
    }