通过结合Combobox和串行计数的值来创建字符串



现在,我的计数输出是Combobox中的每个元素的0,即它就像B10,B20,B30(B是默认值,下一个项是来自数据库的值,而0在此串联字符串中显示计数)...我的计数没有增加

我该怎么办,当我从jcombobox中选择一个值时我的计数会增加然后按按钮,即我获取B10,B11,B12,B20,B21,B22,B22,B30,B31,B32,B32

           public void actionPerformed(ActionEvent ae) {
           String str = ae.getActionCommand();
           if (str.equals("GENERATE PART NO. :")) {
           try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
            st = con.createStatement();
            String s = "select value from user1 where Userdata='" + jc.getSelectedItem() + "'";
            rs = st.executeQuery(s);
            t1.getText();
            if (rs.next()) {
                int j = 0;
                String add1 = rs.getString("value");
                t1.setEditable(false);
                String str9 = new String();
                str9 = "B" + add1; //B is the default value, add1 is the value from database  
                String str10 = new String();
                str10 = str9 + j;
                String query = "select MC from final";
                ResultSet rs1 = st.executeQuery(query);
                while (rs1.next()) {
                    if (str10.equals(rs1)) {
                        j = j + 1;
                        j=new Integer(j+1);
                        t1.setText(str10);
                    } else {
                        t1.setText(str10);
                    }
                }
            }
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
                String s1 = ("insert into final(MC)values(?)");
                PreparedStatement pstm = con.prepareStatement(s1);
                pstm.setString(1, t1.getText());
                int rowi = pstm.executeUpdate();
                if (rowi > 0) {
                    JOptionPane.showMessageDialog(null, "DATA INSERTED");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, "ERROR CLOSE");
            }
        }

答案很简单:将str10 = str9 + j;移至while主体。

您的(片段)代码应该看起来像:

  /*  if */while(rs.next()) {
       int j = 0;
        String add1 = rs.getString("value");
        t1.setEditable(false);
   // String str9; //= new String(); redundant
        String str9 = "B" + add1; //B is the default value add1 is the value from database  
        String str10 = str9;
        String query = "select MC from final";
        ResultSet rs1 = st.executeQuery(query);
        while (rs1.next()) {   
            if (str10.equals(rs1.getString("MC")) {
                j++; //j = j + 1;
               // j=new Integer(j+1); you simply increment j twice
                str10 = str9 + j;// EDITED LINE!
            }
            t1.setText(str10);  
        }  
    }

最新更新