0

When I run the following code I get an error:

java.lang.String cannot be cast to java.lang.Integer

This is my code:

try{
       int rows = jTable1.getRowCount();
       String myUrl = "jdbc:mySql://localhost:3306/hospital"; 
       Connection con = DriverManager.getConnection(myUrl,"root","");
       con.setAutoCommit(false);


            String query = "Insert into `test and treatment_has_admission`(`Test and Treatment_id`,`Admission_a_id`,`Test_Result`,`Treatment_Result`,`Date`)"+" values (?, ?, ?, ?, ?)";
            PreparedStatement pst = con.prepareStatement(query);
            for(int row=0; row<rows; row++){
                int TestTreatmentID = (int) jTable1.getValueAt(row, 1);
                String test_result = (String) jTable1.getValueAt(row, 2);
                String treatment_result = (String) jTable1.getValueAt(row, 3);
                String Date = (String) jTable1.getValueAt(row, 4);
                pst.setInt(1,TestTreatmentID);
                pst.setInt(2,Integer.parseInt(t2.getText()));
                pst.setString(3, test_result);
                pst.setString(4, treatment_result);
                pst.setString(5, Date);

                pst.addBatch();
            }
            pst.executeBatch();
            con.commit();
            con.close();
        }


    catch(Exception e){
        e.printStackTrace();
    }



}     

Error: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

Why am I receiving such an error? Please help me to resolve it.

cosmoonot
  • 2,161
  • 3
  • 32
  • 38
maneesha
  • 145
  • 2
  • 4
  • 12
  • It seems your answer here: http://stackoverflow.com/questions/14921446/getting-value-from-jtable-as-integer – taile May 10 '17 at 06:19
  • 4
    That is so **weird**!!!! 5 lines down, you know how to use `Integer.parseInt()` to convert a `String` to an `int`. How come you don't know that 5 lines before?!?!?!? – Andreas May 10 '17 at 06:21

4 Answers4

1

String can't cast into Integer. Use this

 int TestTreatmentID = Integer.parseInt(jTable1.getValueAt(row, 1));

EDIT

 String string= jTable1.getValueAt(row, 1).toString();
 int TestTreatmentID = Integer.parseInt(string);
Abhishek Aryan
  • 19,936
  • 8
  • 46
  • 65
0

It seems you got problem at line

int TestTreatmentID = (int) jTable1.getValueAt(row, 1);

Let's use Integer.parseInt instead

Integer TestTreatmentID = Integer.parseInt(jTable1.getValueAt(row, 1).toString());
taile
  • 2,738
  • 17
  • 29
0

You cannot simply typecast integers like this

int TestTreatmentID = (int) jTable1.getValueAt(row, 1);

Instead, parse this string to get proper integer value

int TestTreatmentID = Integer.parseInt(jTable1.getValueAt(row, 1));
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
0

You need to parse the value returned from method to Int using

Integer.parseInt(jTable1.getValueAt(row, 1));
saum22
  • 884
  • 12
  • 28