在 net beans 中添加新元素后立即对数组列表的元素求和会导致添加的第一个元素不计入总和中。然后,当我添加另一个元素时,它只会对添加的第二个元素求和。代码如下是我的问题的图像。
https://gyazo.com/12f13ab5724af3de8d9848994987910d
private void balanceAddActionPerformed(java.awt.event.ActionEvent evt) {
try {
outputBox.setText("");
String check = addInput.getText();
int check1 = check.length();
if ("".equals(check)) {
errorLabel.setText("Nothing has been entered to be added.");
for (int i = 0; i < balance.size(); i++) {
outputBox.setText(outputBox.getText() + balance.get(i) + "\n");
}
} else if (check1 >= 7) {
errorLabel.setText("Too many characters limit your characters to 7");
addInput.setText("");
for (int i = 0; i < balance.size(); i++) {
outputBox.setText(outputBox.getText() + balance.get(i) + "\n");
}
} else {
double list = Integer.parseInt(addInput.getText());
balance.add(list);
addInput.setText("");
//Setting the array list in outputbox
for (double i = 0; i < balance.size(); i++) {
outputBox.setText(outputBox.getText() + balance.get((int) i) + "\n");
errorLabel.setText("");
double sum = 0;
for (double j = 1; j < balance.size(); j++) {
sum += balance.get((int) j);
String converted = String.valueOf(sum);
errorLabel.setText("Your sum is " + (converted));
}
}
}
} catch (Exception e) {
errorLabel.setText("Error wrong characters.");
for (int i = 0; i < balance.size(); i++) {
outputBox.setText(outputBox.getText() + balance.get(i) + "\n");
}
}
}
最佳答案
主要问题是您在 1
处开始求和循环,这就是跳过第一个索引 0
的原因:
for(int j=0; j<balance.size(); j++){
sum += balance.get(j);
}
String converted = String.valueOf(sum);
errorLabel.setText("Your sum is " + (converted) );
其他旁注:
- 无需将
j
声明为double
(然后将其转换回int
) - 无需更新循环内的标签。一旦循环完成计算总和,您就可以执行此操作。
为了使整个事情更清晰,您可以使用
for-each
循环,因为您不需要索引(并且因为ArrayList
是可迭代的)for(double b: balance){ sum += b; }
关于java - 在 net beans 中添加新元素后对数组列表中的元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37645237/