java.lang.NumberFormatException:对于输入字符串:“”保存到数据库时

时间:2016-12-09 04:43:30

标签: java mysql netbeans

我想添加新房间,我会在文本字段中输入房间详细信息Room Number, Room type, Bed number and Rates,当我点击保存时,我收到错误java.lang.NumberFormatException: For input string: ""

错误源自at RoomMang.jButton1ActionPerformed(RoomMang.java:352) fetchFromTextF();函数。请参见图像:RoomMgt

我使用System.out.println (insertquery);的插入语句如下所示: insert into roomdetail(room_no,room_type,room_rate,room_bed)values('','','','');

这是我从文本字段中获取数据的方式:

public void fetchFromTextF(){
    rno=rnumber.getText();
    rtype=jTextField2.getText();
    rrate=Integer.parseInt(jTextField3.getText());
    rbed=jTextField4.getText();
}

这是我执行的保存操作按钮:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        clearTextF();
        enableTextF();
        String query = "SELECT * FROM roomdetail where room_no like '" +           rnumber.getText() + "';";
        smt = con.createStatement();
        rs1 = smt.executeQuery(query);
        if (!rs1.next()) {
            try {
                if (evt.getActionCommand().equals("Save")) {
                    fetchFromTextF();
                    int code = JOptionPane.showConfirmDialog(this, "Information of Room No." +rno+ " will be added in database.", "Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
                    if (code == JOptionPane.YES_OPTION) {
                        String insertquery = "insert into roomdetail(room_no,room_type,room_rate,room_bed)values('" +rno + "','" + rtype + "'," + rrate + ",'" + rbed + "');";
                        smt = con.createStatement();
                        int success = smt.executeUpdate(insertquery);
                        if (success > 0) {
                            JOptionPane.showMessageDialog(this, "Record Saved");
                            jButton1.setText("New");
                        } else {
                            JOptionPane.showMessageDialog(this, "Problem in Saving. Retry");
                        }
                    } else {
                    }
                } else if (evt.getActionCommand().equals("New")) {
                    clearTextF();
                    jButton1.setText("Save");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            JOptionPane.showMessageDialog(this, "Room No. already used, Give another Room No.");
        }
    } catch (Exception ex) {
    }
}             

1 个答案:

答案 0 :(得分:1)

jTextField3中的值为空,因此以下内容将失败

rrate=Integer.parseInt(jTextField3.getText());

可能会改为

rrate = -1;
if (jTextField3.getText().trim().length() > 0) {
  rrate=Integer.parseInt(jTextField3.getText());
}

或只是捕捉异常

try {
   rrate=Integer.parseInt(jTextField3.getText().trim ());
}
catch (NumberFormatException ex) {
    System.err.println (ex);
    rrate = -1;
}