我想从JComboBox
获取所选值,在数据库中搜索并使用JTextField
中的值更新数据库中的数量。这是代码:
Object selected = jComboBox1.getSelectedItem();
String album = (String)selected;
int qty=Integer.parseInt(jTextField7.getText());
String query2="update productlist set QtyAvail=? " +
"where Album=?";
try
{
PreparedStatement ps2=con.prepareStatement(query2);
ps2.setInt(1, qty);
ps2.setString(2,album);
int res1=ps2.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
}
我收到了这个错误:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException:
For input string: " 1"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at AddProductPanel.jButton2ActionPerformed(AddProductPanel.java:341)
at AddProductPanel.access$4(AddProductPanel.java:335)
at AddProductPanel$5.actionPerformed(AddProductPanel.java:133)
我在文本字段中输入了值“1”。
答案 0 :(得分:5)
输入parseInt()
的字符串中有一个空格,使用trim()
答案 1 :(得分:4)
我想从
JComboBox
获取所选值,在数据库中搜索并使用JTextField
中的值更新数据库中的数量。
将JFormattedTextField
与Number Formatter
或者更好的是使用JSpinner
和SpinnerNumberModel
避免在数据类型之间进行解析,可以控制输入的值(min - max - ev。范围 - 十进制形式)
答案 2 :(得分:2)
您的字符串包含空格。
在解析之前使用trim:
int qty=Integer.parseInt(jTextField7.getText().trim());
答案 3 :(得分:1)
@Nivedita Gautam:a blank
之前似乎附加了1
个空格。
尝试使用以下语句:
int qty = Integer.parseInt(jTextField7.getText().trim());