簡體   English   中英

在Net Bean中添加新元素后,對數組列表中的元素求和

[英]Summing elements in an Array List after adding a new element in net beans

在net bean中添加一個新元素后立即對數組列表中的元素求和會導致添加的第一個元素不計入總和。然后當我添加另一個元素時,它只會對添加的第二個元素求和。代碼在下面並且有一個圖像我的問題。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM