在网络bean中添加新元素后立即对数组列表的元素进行求和导致添加的第一个元素不计入总和。然后,当我添加另一个元素时,它只对添加的第二个元素求和.Code在下面和那里是我的问题的形象。
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");
}
}
}
答案 0 :(得分:1)
主要问题是你在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;
}