英文:
Error in Java project: Type mismatch: cannot convert from element type Object to JSONObject
问题
我遇到了这个错误:“类型不匹配:无法从元素类型Object转换为JSONObject”。
我不知道要更改什么,因为我的transactions是一个JSONObjects的JSONArray。是否有人知道为什么会出现这个问题以及如何修复它?谢谢!
for (JSONObject transaction : transactions) {
if (transaction.getString("direction").equals("OUT")) {
int amount = transaction.getInt("amount");
int rounded = (amount + 99) / 100 * 100;
int roundUpAmount = rounded - amount;
roundUpAmounts.add(roundUpAmount);
}
}
return roundUpAmounts;
}```
<details>
<summary>英文:</summary>
I am getting this error: "Type mismatch: cannot convert from element type Object to JSONObject".
I don't know what to change because my transactions is a JSONArray of JSONObjects. Does anyone have an idea why this is happening and how to fix it? Thanks!
``` public ArrayList<Integer> roundUpArray(JSONArray transactions) {
for (JSONObject transaction : transactions) {
if (transaction.getString("direction").equals("OUT")) {
int amount = transaction.getInt("amount");
int rounded = (amount + 99) / 100 * 100;
int roundUpAmount = rounded - amount;
roundUpAmounts.add(roundUpAmount);
}
}
return roundUpAmounts;
}
</details>
# 答案1
**得分**: 1
如果您明确转换数组的每个元素,它应该正常工作。
像这样:
```java
for (Object obj : transactions) {
JSONObject transaction = (JSONObject) obj;
if (transaction.getString("direction").equals("OUT")) {
int amount = transaction.getInt("amount");
int rounded = (amount + 99) / 100 * 100;
int roundUpAmount = rounded - amount;
roundUpAmounts.add(roundUpAmount);
}
}
英文:
If you cast each element of the array explicitly, it should work.
Like this:
for (Object obj : transactions) {
JSONObject transaction = (JSONObject) obj;
if (transaction.getString("direction").equals("OUT")) {
int amount = transaction.getInt("amount");
int rounded = (amount + 99) / 100 * 100;
int roundUpAmount = rounded - amount;
roundUpAmounts.add(roundUpAmount);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论