【问题标题】:error check the empty textField of int values错误检查 int 值的空 textField
【发布时间】:2020-07-23 06:16:42
【问题描述】:

代码如下:

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);


}

这是错误:

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

该代码可能适用于字符串文本字段,但不适用于整数文本字段。
如果我删除它可能会起作用:

 txtid.getText().isEmpty()

请告诉我如何修复代码?

【问题讨论】:

  • 你能显示这段代码中引用的相关类和对象吗? IE;日期、txtname、txtid。
  • int id = Integer.parseInt(txtid.getText());
  • 这不是我问的。另外,用我要求的信息更新主帖,而不是后续的 cmets。
  • 我做编辑

标签: java swing netbeans int jtextfield


【解决方案1】:

似乎 txtid.getText() 正在返回“”。那是对的吗? 字符串“”不是数字,不能被 Integer.parseInt() 解析。您可以做的一件事是使用 try, catch。如果它抛出 NumberFormatException 错误,您可以相应地处理它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2022-06-19
    • 2021-08-04
    • 1970-01-01
    • 2021-09-01
    • 2022-08-06
    相关资源
    最近更新 更多