Komal Patil
Komal Patil

Reputation: 13

JTextfield Validation for numbers?

I am trying to validate my roll no (input of integer value) from JTextField. Well my code is compiling but while running it is giving me an error NumberFormatException. Here is my validation code

public int rno_vd() {
    int a=0,b=0,c=0,x=0,y=0;
    int vrno =Integer.parseInt(txtRno.getText());
    String r = String.valueOf(vrno);
    if (r.isEmpty()) {
        JOptionPane.showMessageDialog(null,"rno should not be empty");
        a=1;
    }
    else if (Pattern.matches("[a-zA-Z]+",r)) {
        JOptionPane.showMessageDialog(null,"rno should be in digits");
        b=1;
    }
    else if (vrno < 0) {
        JOptionPane.showMessageDialog(null,"rno cannot be negative");
        c=1;
    }
    System.out.println(a + b + c);
    if (a==1 || b==1 || c==1) {
        x=1;
        return x;
    }
    else {
        y=0;
        return y;
    }
}

error

C:\Users\Hp\Desktop\jproject>javac -cp hibernatejar\*  *.java
Note: DBHandler.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

C:\Users\Hp\Desktop\jproject>java -cp hibernatejar\*;.  Sms
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
        at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
        at java.base/java.lang.Integer.parseInt(Integer.java:662)
        at java.base/java.lang.Integer.parseInt(Integer.java:770)
        at AddFrame.lambda$new$1(AddFrame.java:80)
        at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
        at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
        at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
        at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
        at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
        

Upvotes: 0

Views: 350

Answers (2)

Divesh Harchandani
Divesh Harchandani

Reputation: 1

Komal here as I can see you want to validate JTextField for roll numbers ie should only contain integers, any other character instead of numbers should not be accepted... Well, I suggest you to try validating on every keyReleased using KeyListener of KeyEvent. Every key you press is validated if its number its good to go if its not it will show Dialog box saying "only numbers accepted".

I am sharing my code I hope it might help

//********function to check if value is numric or not*********
public static boolean isNumeric(String str) { 
        try {  
            Integer.parseInt(str);  
            return true;
        } 
        catch(NumberFormatException e){  
            return false;  
        }  
    }
//************************function ends******************************


//txtRno is my JTextField 

txtRno.addKeyListener(new KeyListener(){
        public void keyPressed(KeyEvent e)
        {
            //code      
        }
        public void keyReleased(KeyEvent e)
        {
            String value = txtRno.getText();
            int l = value.length();
            if(!isNumeric(value) && l>0){//if not numric it will not allow you to edit JTextField and show error message
                txtRno.setEditable(true);
                JOptionPane.showMessageDialog(c,"You need to enter number","ERROR",JOptionPane.ERROR_MESSAGE);
                txtRno.requestFocus();
                txtRno.setText("");
                txtRno.setEditable(true);
                lblError.setText("");
            } 
            else { //else it will take the input as it already number or integer 
                txtRno.setEditable(true);
                lblError.setText("");
            }
        }
        public void keyTyped(KeyEvent e)
        {
            //code
        }
    });

Upvotes: 0

Arindam Roy
Arindam Roy

Reputation: 111

It is getting NumberFormatException, when text field has empty value.

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""

Could you please try to validate the text first, and then parse the string?

    // Validating text input first
    String r = txtRno.getText();

    if (r.isEmpty())
        {JOptionPane.showMessageDialog(null,"rno should not be empty");
            a=1;}
    else if (Pattern.matches("[a-zA-Z]+",r))
        {JOptionPane.showMessageDialog(null,"rno should be in digits");
            b=1;}
    else if (vrno < 0)
        {JOptionPane.showMessageDialog(null,"rno cannot be negative");
            c=1;}

    // Converting to int, if validation is successful
    int vrno =Integer.parseInt(txtRno.getText());

Upvotes: 1

Related Questions