gpt4 book ai didi

java - 使用循环计算多个字符串值的总和

转载 作者:行者123 更新时间:2023-12-02 09:26:43 25 4
gpt4 key购买 nike

enter image description here我有一个名为 Price 的字符串。我从 firebase 数据库中获取 Price 的值。我想对这些字符串值求和并得出总价格。价格的值根据数据库中的子项自动增加。例如值为100、70、50、20、40等,并且会相应增加。

我认为应该有一个循环来计算所有这些值的总和,使其成为总价。

这就是我到目前为止所做的。

 int pos = 0;                                     
JSONObject jsonObject = new JSONObject();
if (jsonObject.has(Integer.toString(pos))) {
} else {
try {
jsonObject.put(Integer.toString(pos),Price);
} catch (JSONException e) {
e.printStackTrace();
}
}

for (int i = 0; i < jsonObj.length(); i++) {
try {
String itemInArray = jsonObj.getString(String.valueOf(i));
int Sum = 0;
int totalPrice = sum + itemInArray;

} catch (JSONException e) {
e.printStackTrace();
}

}

但是代码不起作用。请提供任何帮助,我们将不胜感激。

最佳答案

让我们隔离代码中出现问题的部分,使用循环求和大量字符串值

for (int i = 0; i < jsonObj.length(); i++) {
try {
String itemInArray = jsonObj.getString(String.valueOf(i));
int Sum = 0;
int totalPrice = sum + itemInArray;

} catch (JSONException e) {
e.printStackTrace();
}

}

每次循环执行此代码时,都会将 0 的值重新分配给 Sum,因此 totalPrice 的值始终为 0 加itemInArray(另一个问题是,它是一个字符串,不能直接添加到整数)。

假设其他一切都正确,并且 itemInArray 保存一个数值,这里是查找总价的代码:

try{
int sum = 0; // you don't need the totalPrice variable, they will hold the same result
for (int i=0;i<jsonObj.length(); i++) {
String itemInArray = jsonObj.getString(String.valueOf(i));
int itemPrice = Integer.ParseInt(itemInArray);
sum = sum + itemPrice;
}
}catch (JSONException e) {
e.printStackTrace();
}

现在,sum 不会在每个循环中重新定义,它会保留上一个循环中的值,并在下一次迭代中添加自身和 itemPrice

关于java - 使用循环计算多个字符串值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58293840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com