0

I'm facing a problem here while trying to get the double sum of a jtable column. My table gets only 3 columns from a mySQL table. One of the columns is DATE type, and the other two are DOUBLE type. So when i try:

double xreoseistot = 0;
double xreosi;
for(int i = 0; i < jTable1.getRowCount(); i++){


    xreosi = Double.parseDouble((String)jTable1.getValueAt(i, 2));
    xreoseistot += xreosi;}

I get an error saying: "Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.sql.Date cannot be cast to java.lang.String"

So the question is, why my code tries to get all of the table converted to String and not just the column and also, what's the solution to this?

JohnK
  • 21
  • 3
  • Possible duplicate of [Explanation of "ClassCastException" in Java](https://stackoverflow.com/questions/907360/explanation-of-classcastexception-in-java) – Sergiy Medvynskyy Jun 12 '17 at 13:04

3 Answers3

0

From your error message it appears that the third column being returned is a java.sql.Date, not a string. Hence, it does not make good sense to try to cast this to a string, nor should you expect that summing a string as a number would make any sense.

Instead, you can try summing the milliseconds representing each of the dates in your result set:

for (int i=0; i < jTable1.getRowCount(); i++) {
    xreosi = Double.parseDouble((double)jTable1.getValueAt(i, 2).getTime());
    xreoseistot += xreosi;
}

If you intend to sum the other two columns, which presumably are doubles, then you should change the column index in your for loop, e.g.

for (int i=0; i < jTable1.getRowCount(); i++) {
    xreosi = Double.parseDouble(jTable1.getValueAt(i, 1)); // assuming 2nd column is double
    xreoseistot += xreosi;
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Problem is here:

Exception in thread AWT-EventQueue-0 java.lang.ClassCastException: java.sql.Date cannot be cast to java.lang.String

Why are you trying to calculate with Date? What is your intention? How would you like to manipulate with Date parts? - day, month...

1ac0
  • 2,875
  • 3
  • 33
  • 47
0

Turns out, just my syntax was wrong, i didn't want to calculate the dates. I meant column 1, sorry guys and thanks

JohnK
  • 21
  • 3