在网络bean中添加新元素后对数组列表中的元素求和

时间:2016-06-05 18:16:39

标签: java arrays netbeans sum element

在网络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");
        }
    }
}

1 个答案:

答案 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;      
    }