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
  • 45,262
  • 17
  • 54
  • 100
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,182
  • 6
  • 46
  • 71
0

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

pomkine
  • 1,575
  • 4
  • 17
  • 29