I tried your code. It works if I type in the JTextField
with numbers that are not 7. If I type letters, the pop-up warning will not show. I assume that it did not work when you typed letters, not numbers.
Here is the thing: try ... catch
block is use to catch exception
. If you type numbers, double.parseDouble
will work, so there will be no exception
in the try
block to be catched, and you see the warning message if the condition in the while
not met.
If you type letters, the double.parseDouble
will throws exception because converting letters to double is not allowed. Instead of moving to next line (the while loop), it will jump to the catch
block to handle the exception, but you do not specify how to do that, and you will not see any the warning message.
So, the solution is simple: add an action to catch
block to do something when the double.parseDouble
throws an exception, like showing a message:
try
{
Double user_input = Double.parseDouble(jTextField1.getText());
while (user_input != 7)
{
JOptionPane.showMessageDialog(null, "Please type number 7", "Error", JOptionPane.ERROR_MESSAGE);
break;
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Please type numbers", "Error", JOptionPane.ERROR_MESSAGE);
}
You may notice that by using while
the warning message keeps showing because the condition always true
with the input not 7. So change to if
as @Hades answer or add break
to make it show 1 time only.
I prefer if
.