gpt4 book ai didi

java.lang.NumberFormatException : For input string: "" while saving to database 异常

转载 作者:行者123 更新时间:2023-11-28 23:22:14 24 4
gpt4 key购买 nike

我想添加新房间,我会在文本字段中输入房间详细信息、房间号、房间类型、床号和价格,当我点击保存时,出现错误java.lang.NumberFormatException:对于输入字符串:“”

错误源自 at RoomMang.jButton1ActionPerformed(RoomMang.java:352),这是 fetchFromTextF(); 函数。参见图片:RoomMgt

我使用 System.out.println (insertquery); 的插入语句如下所示:插入 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) {
}
}

最佳答案

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

关于java.lang.NumberFormatException : For input string: "" while saving to database 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41053255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com