0

I'm having problems when taking a value out of a list and then casting it as an integer so I then can use it for different math functions, such as multiplication.

Current code :

int i = 0;
while(i < student_id.size()){
    String finding = student_id.get(i).toString();
    int s101 = ((Integer)score101.get(student101.indexOf(finding))); // <----this is where im having problems
    System.out.println(student_id.get(i)+" "+names.get(i));
    System.out.println("IR101 " + 
                       score101.get(student101.indexOf(finding)) +
                       " IR102 " +
                       score102.get(student102.indexOf(finding)));
    i++;
}

The error that im getting is java.lang.String cannot be cast to java.lang.Integer. This confuses me because I thought it would have been an object. I have tried to convert it to an integer from both an object and a String but both throw up errors. How can I convert score101.get(student101.indexOf(finding)) to an int ?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
user3077551
  • 69
  • 2
  • 9

2 Answers2

1

The error is pretty clear, java.lang.String cannot be cast to java.lang.integer.

That means score101.get(student101.indexOf(finding)) return a String. If the string represent an Integer then you can parse it easily

Integer.parseInt(score101.get(student101.indexOf(finding)))

Edit

As per your comment, the string is a Double so you need to use parseDouble

Double.parseDouble(score101.get(student101.indexOf(finding)))

If you really want it as an int and discard the decimal, you can call intValue() which will cast it to an int (or cast directly).

Double.parseDouble(score101.get(student101.indexOf(finding))).intValue()
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • but this is rounding up? say the value 35.6 and 20.7 are added together this could then return 55.0 and not 36.3? – user3077551 Apr 02 '15 at 13:42
  • @user3077551 Yep, that is why I would recommend to keep the double if you need them. If you really need an int as final value, then do all the calculation in double and at first retrieve it int value. – Jean-François Savard Apr 02 '15 at 13:47
0

You can parse string with Integer.parseInt(String s) method

pomkine
  • 1,605
  • 4
  • 18
  • 29