java - 在 net beans 中添加新元素后对数组列表中的元素求和

标签 java arrays netbeans sum element

在 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/

相关文章:

javascript - Angular JS ng-repeat 不适用于对象数组

php - 如何获取自定义元数据

netbeans - 有没有一种方法可以使Netbeans文件上传不会因单个错误而失败?

java - 使用 deeplearning4j 加载 nlp 模型的问题

java - xml使用sax解析器从子标签解析数据

jquery - 拆分数组并将其放在每个数组的 IF 语句中

php - 使用 PHP 的内置服务器设置 Eclipse PDT

java.sql.SQLException : Opening db :'DB-NAME.sqlite' : Permission denied

java - 在继续 Android 之前等待 GPS 位置

java - 使用 Eclipse JDT AST 从注释获取完全限定名称