Link to home
Start Free TrialLog in
Avatar of chandanchoubey
chandanchoubey

asked on

How do I make a text field only to accept mathematical operators as first character of input.

How do I make the text field to accept mathematical operators (+, -, *, /) only at char(0). nowhere else. My code lets the program accept the mathematical operators everywhere. Please check my code. I am using netbeans
private void txtNumberActionPerformed(java.awt.event.ActionEvent evt) {
        // Action Listner handling code here:
           if(txtNumber.getText().charAt(0) == '+' ||
              txtNumber.getText().charAt(0) == '-' ||
              txtNumber.getText().charAt(0) == '*' ||
              txtNumber.getText().charAt(0) == '/')
         {
     dataDisplay.append(txtNumber.getText()+ '\n');
     txtNumber.setText(null);
        }
         else
         {
      JOptionPane.showMessageDialog(null,"Sorry, " + txtNumber.getText() +
              " is not a valid entry" + "\n" + "Examples of valid Entry are:"
              + "\n" + "+23.5  " + "-1  " + "/6  " + " *12");
            }
    }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of basav_com
basav_com
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of chandanchoubey
chandanchoubey

ASKER

Thanks basav_com. I appreciate your help. But if I input ++40 or --40. It accepts. I want only +40 or -40 to accept. If you can help me with this that will be great!
Thanks basav_com. I appreciate your help. But if I input ++40 or --40. It accepts. I want only +40 or -40 to accept. If you can help me with this that will be great!