Search code examples
javaswingnetbeansintjtextfield

error check the empty textField of int values


Here is the code:

String name = txtname.getText();
         int id = Integer.parseInt(txtid.getText());
        int pass = Integer.parseInt(txtpass.getText());
         String day = Date.getSelectedItem().toString();


    if (txtname.getText().isEmpty() ||txtid.getText().isEmpty()||Date.getSelectedIndex()==0 || event == null||time==null) {


        JOptionPane.showMessageDialog(null, "you should add all information", "error", JOptionPane.ERROR_MESSAGE);



    }                                       

    else {

        ((DefaultListModel) jList1.getModel()).addElement(txtname.getText() + " " + txtpass.getText() + "(" + Date.getSelectedItem() + ") "+event+", "+time);
   try{
               Statement stmt = con.createStatement();
                stmt.execute("INSERT INTO company(name,id) VALUES('"+name+"',"+id+");");
                stmt.execute("INSERT INTO events(pass,time,status,day,companyId) VALUES("+pass+",'"+time+"','"+event+"','"+day+"',"+id+");");

               JOptionPane.showMessageDialog(this, "Record Submit");

          }catch(Exception ex){
              JOptionPane.showMessageDialog(this, ex);

             } 


    }


    this.txtname.setText(null);
    this.txtpass.setText(null);
    this.txtid.setText(null);
    this.Date.setSelectedIndex(0);
    this.jCheckBox1.setSelected(false);
    this.jCheckBox2.setSelected(false);
    this.jCheckBox3.setSelected(false);


}

This is the error:

java.lang.NumberFormatException: For input string: ""

The code is work probably with string textFields but does not work with integer textField.
It works probably if I remove:

 txtid.getText().isEmpty()

please show me how can I fix the code?


Solution

  • It seems txtid.getText() is returning "". Is that correct? The string "" is not numeric and cannot be parsed by Integer.parseInt(). One thing you can do is use a try, catch. If it throws a NumberFormatException error, you can then handle it accordingly.