2015-04-02 31 views
0

从列表中取出一个值然后将其转换为整数时,我遇到了问题,因此我可以将它用于不同的数学函数,如乘法。为什么我不能将此字符串作为int来投射?

当前代码:

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++; 
} 

,即时通讯越来越是java.lang.String cannot be cast to java.lang.Integer错误。这让我感到困惑,因为我认为这会成为一个对象。我试图将它从一个对象和一个字符串转换为整数,但都抛出错误。我怎样才能将score101.get(student101.indexOf(finding))转换为int?

+1

使用'interger.parseInt' – 2015-04-02 13:27:01

+0

我曾经尝试这样做。仍然会抛出错误 – user3077551 2015-04-02 13:28:15

+1

那么是什么错误?字符串的价值是什么? – 2015-04-02 13:29:02

回答

1

错误很明显,java.lang.String cannot be cast to java.lang.integer

这意味着score101.get(student101.indexOf(finding))返回String。如果字符串代表Integer,那么你可以很容易地

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

解析它编辑

根据您的评论,该字符串是一个Double,所以你需要使用parseDouble

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

如果你真的想要它作为一个int并丢弃小数,你可以拨打intValue()将其转换为int(或直接投射)。

Double.parseDouble(score101.get(student101.indexOf(finding))).intValue() 
+0

这工作。非常感谢! – user3077551 2015-04-02 13:32:21

+0

@ user3077551不客气。 – 2015-04-02 13:33:01

+0

但这是四舍五入吗?比如说35.6和20.7的值加起来就可以返回55.0而不是36.3。 – user3077551 2015-04-02 13:42:24

相关问题