字符串无法转换为Int

时间:2017-04-28 15:53:50

标签: java string for-loop int

这只是我的代码的一小部分,但我试图遍历两个字符串,在一个字符串中获取第一个数字的值,然后使用该数字作为在另一个字符串中查找的位置,然后将该单词添加到新字符串中。但是它出现了错误" String无法转换为int"有人可以帮忙吗?

krajeeselect2:unselectall

4 个答案:

答案 0 :(得分:0)

使用它将String转换为int

Integer.parseInt(integerString);

完成的代码行:

result += singleWords[Integer.parseInt(wordPositions[i])];

答案 1 :(得分:0)

如果你的wordPositions是一个String数组:

  result += singleWords[wordPositions[i]];

就像你这样做

result += singleWords["value of the wordPositions array at index i"];

但是需要是[]中的int而不是字符串,为什么你有异常String不能强制转换为Int

答案 2 :(得分:0)

如果wordPositions是字符串中的数字数组,例如

String[] wordPositions = new String[]{"1","2","3"};

然后你需要使用

Integer.parseInt(NUMBER_IN_STRING);

将字符串值更改为int值。

答案 3 :(得分:0)

您收到此错误是因为wordPositions [i]返回一个字符串,您需要在尝试访问单字[]之前将其转换为int。

result += singleWords[Integer.parseInt(wordPositions[i])];