有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用JTextField的java无法将值转换为int

我想从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”


共 (4) 个答案

  1. # 1 楼答案

    您的字符串包含一个空格

    解析前使用trim:

    int qty=Integer.parseInt(jTextField7.getText().trim());
    
  2. # 2 楼答案

    I want to get the selected value from JComboBox, search it in database and update the quantity in database with the value in JTextField.

    • ^{}Number Formatter

    • 或者更好的方法是使用^{}SpinnerNumberModel

    • 避免在数据类型之间进行解析,您可以控制输入值(最小-最大-ev.范围-十进制形式)

  3. # 3 楼答案

    @Nivedita Gautam:似乎a blank空格被附加在1之前。 尝试使用以下语句:

    int qty = Integer.parseInt(jTextField7.getText().trim());
    
  4. # 4 楼答案

    在输入到parseInt()的字符串中有一个空格,请使用trim()