-4

i want to make sure data entered by users is not a String and if it's show a message!

String number = JOptionPane.showInputDialog("Enter a number : ",null);

here is more information for what i'm doing

                String guess = JOptionPane.showInputDialog("Enter Your Guess Number : ",null);
                if((Integer.parseInt(guess) < 1))
                {
                 JOptionPane.showMessageDialog(null,"Enter a number Greater than 0!");
                       JOptionPane.showMessageDialog(null, "you won 1,000 $", "winner!"
                            , JOptionPane.INFORMATION_MESSAGE);
                }
Mohammadreza Khatami
  • 1,444
  • 2
  • 13
  • 27

3 Answers3

2

You can achieve it by parsing the value entered by the user and if it's not a valid number then show the error dialog using JOptionPane.showMessageDialog. E.g.

String number = JOptionPane.showInputDialog("Enter a number : ",null);
boolean isValidNumber = false;
try {
    System.out.println(Integer.parseInt(number));
    isValidNumber  = true;
} catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(new JPanel(), "Invalid number", "Error", JOptionPane.ERROR_MESSAGE);
}
sol4me
  • 15,233
  • 5
  • 34
  • 34
2

If you expect an integer, this should do it

boolean isInteger = false;
try {
    int foo = Integer.parseInt(number);
    isInteger = true;
} catch (NumberFormatException) {
    // it's not a integer, handle the exception
}
Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • nop,i have a random generator not scanner, and i want check user guess,tnx for your answer – Mohammadreza Khatami Dec 25 '14 at 14:14
  • 1
    This code checks if some string (`number` variable) can be parsed to Integer or not, it doesn't have anything to do with scanner. Weather you get that `number` from scanner, random generator, web service or something else is totally irrelevant. – Predrag Maric Dec 25 '14 at 14:19
1

Another approach is to verify that the value entered is a number BEFORE closing the option pane.

Read the section from the Swing tutorial on Stopping Automatic Dialog Closing for an approach that will allow you to validate the text entered before closing the dialog.

camickr
  • 321,443
  • 19
  • 166
  • 288