number validation in Java

How can I check the validation of numbers in TextField,I mean that the users must be able to enter numbers only (like 30,3000,56.76,....), so it must show a message box if any other character that is not a number is entered.
urmilaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

yongsingCommented:
Use the Double.parseDouble() method to validate the text is a floating point number, or use Integer.parseInt() if you want it to be an integer.

textField.addActionListener(
 new ActionListener() {
   public void actionPerformed(ActionEvent actionEvent) {
     TextField tf = (TextField)actionEvent.getSource();
     String text = tf.getText();
     try {
        double number = Double.parseDouble(text);
     } catch (NumberFormatException e) {
        // Show error message here.
        return;
     }
     // String is ok. Do what you want with it here.
   }
 }
);
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
PiterCommented:
If you are using JSP or servlets.
 Make one validation.js file and on Submit button check validation for each check box.
 if you want i can give you the code. its little bit leangthy but it will check for each char entered in that text box.


reply,

piter
0
umangjoshiCommented:
Pls use javax.swing.JFormattedTextField
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

CEHJCommented:
If you are not using Swing, you'll have to add a KeyListener to the field that restricts entry. Better is to use Swing and call

jTextField.setDocument(new DecimalDocument(2));// for two decimal places

with something like the class below:

class DecimalDocument extends PlainDocument {
  int decimalPlaces;
  int pointPosition;
  boolean badChars;
  StringBuffer buffer;

  public DecimalDocument(int decimalPlaces) {
    super();
    this.decimalPlaces = decimalPlaces;
    pointPosition = -1;
    buffer = new StringBuffer();
  }

  public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {

    try {
      buffer.append(getText(0, getLength())).append(str);
      for(int i = 0; i < buffer.length(); i++) {
        if (!(Character.isDigit(buffer.charAt(i)) || buffer.charAt(i) == '.')) {
          badChars = true;
        }
        if (buffer.charAt(i) == '.') {
          if (pointPosition == -1) {
            pointPosition = i;
          }
          else {
            badChars = true;
          }
        }
      }
      // Now validate decimal places
    }
    finally {
      if (!badChars) {
        if (pointPosition < 0) {
          super.insertString(offs, str, a);
        }
        else {
          if ((buffer.length() - 1 - pointPosition) <= decimalPlaces) {
            super.insertString(offs, str, a);
          }
        }
      }
      reset();
    }
    try {
      Integer.parseInt(str);
    }
    catch(NumberFormatException e){
      //e.printStackTrace();
      return;
    }
    // str is an integer
    if (getLength() + str.length() <= decimalPlaces) {
      super.insertString(offs, str, a);
    }

  }

  void reset() {
    pointPosition = -1;
    badChars = false;
    buffer.setLength(0);
  }
}


0
urmilaAuthor Commented:
Yes,it's working
Thank u
0
CEHJCommented:
That won't stop anything other than numbers being entered, as your question specified:

>>I mean that the users must be able to enter numbers only
0
yongsingCommented:
If he is using a TextField, there's nothing much he can do to prevent the user from entering numbers only. Adding a key listener won't help much because the user can still do a copy & paste (of non-number characters) onto the TextField.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.