【问题标题】:Calculate Sum using ArrayList使用 ArrayList 计算总和
【发布时间】:2017-10-15 08:57:34
【问题描述】:

我正在创建一个 SpringServiceImpl 类,它将在列表中计算总借方金额。但是,我收到一个错误:The operator += is undefined for the argument type(s) List<GeneralLedgerEntity>, GeneralLedgerEntity

List<GeneralLedgerEntity> calculateResult = new ArrayList<>();
for(GeneralLedgerEntity credit : calculateResult){
    calculateResult += credit;
    return calculateResult;
}

这个选项应该是什么?

【问题讨论】:

  • calculateResult 是你的列表,我想你想在这里有一个数值
  • 请更正您的问题,您不能对数组列表执行 +=。我猜你已经忘记了 java,我不知道人们在假设和回答你的问题
  • 你想做什么?要么计算一个总数,但你没有创建一个数字变量来存储一个总数,或者列出所有 GeneralLedgerEntity 的列表,但你正在循环一个空列表。

标签: java spring arraylist


【解决方案1】:

您正在尝试对 GeneralLedgerEntity 对象求和,Java 没有运算符重载(字符串除外)。

您需要添加此对象所包含的值,例如,如果您在 GeneralLedgerEntity 类中有一个名为 debitAmount 的字段,则执行以下操作:

calculateResult += credit.debitAmount

而且你的for循环中有一个return语句,这没有意义,它只会执行一次,将return语句移到循环之后。

【讨论】:

  • calculateResult 是一个列表,而不是一个数字。
【解决方案2】:

您不能在 Java 中使用 + 运算符。相反,您必须在 SpringServiceImpl 类中实现 plusadd 方法。

class Point{
    public double x;
    public double y;

    public Point(int x, int y){
        this.x = x;
        this.y = y;
    }

    public Point add(Point other){
        this.x += other.x;
        this.y += other.y;
        return this;
    }
}

用法

Point a = new Point(1,1);
Point b = new Point(2,2);
a.add(b);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 2018-10-10
    • 2011-11-13
    • 2019-05-05
    相关资源
    最近更新 更多