You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java静态方法无法返回正确总价值问题排查求助

问题描述

我有First和Second两个Java类,First类仅包含main()方法,Second类会被实例化多次。需求是从First类调用Second类的静态方法,返回所有Second实例的总价格。当前代码无报错,但输出结果不符合预期,请问问题出在add()、increaseTotalCost()还是getTotalCost()方法中?

编写的代码

Second类代码

public class Second {

    private static int totalCost = 0;
    private int totalPrice = 0;
    
    public static void increaseTotalCost(int totalPrice) {
        Second.totalCost += totalPrice;
    }
    
    public void add(String name, int price, int count) {
        totalPrice += count * price;
        increaseTotalCost(totalPrice); 
    }

    public static int getTotalCost() {
        return Second.totalCost;
    }
    public int getTotalPrice() {
        return totalPrice;
    }
}

First类代码

public class First {

   public static void main(String[] args) {

          Second test1 = new Second();
          test1.add("someName", 200, 1);
          test1.add("randomName", 140, 1);

          Second test2 = new Second();
          test2.add("anotherName", 9670, 3);

          System.out.println("The overall price is: " + 
          Second.getTotalCost());
  }
}

实际测试代码及结果

public class First {
    public static void main(String[] args) {
        Second test1 = new Second();
        test1.add("anyName", 1, 1);
        test1.add("randomName", 2, 1);

        Second test2 = new Second();
        test2.add("xxx", 3, 1);
        test2.add("yyy", 5, 1);
        test2.add("zzz", 1, 1);

        System.out.println("test1 : " + "\nTotal Price: " + 
            test1.getTotalPrice()); // 输出3
        System.out.println("test2 : " + "\nTotal Price: " + 
            test2.getTotalPrice()); // 输出9

        System.out.println("Total cost of all instances: " + 
            Second.getTotalCost()); // 输出24
    }
}
问题根源与解决方案

问题出在**add()方法**里。

原因分析

每次调用add()时,你传递给increaseTotalCost()的是当前实例累计后的totalPrice,而非本次add操作新增的价格。以测试代码为例:

  • test1第一次add后,totalPrice=1,totalCost变为1;第二次add后,totalPrice=3,又将3加到totalCost,此时totalCost=1+3=4;
  • test2第一次add后totalPrice=3,totalCost变为4+3=7;第二次add后totalPrice=8,totalCost变为7+8=15;第三次add后totalPrice=9,totalCost变为15+9=24,这就是输出24的原因。

但实际需求是统计所有实例的总价格之和(3+9=12),或等价于每次add新增价格的总和(1+2+3+5+1=12)。

修正方案

方案一:修改add()方法,传递新增价格

只需要在add()中计算本次新增的价格,再传递给静态方法:

public void add(String name, int price, int count) {
    int addedPrice = count * price;
    totalPrice += addedPrice;
    increaseTotalCost(addedPrice); 
}

方案二:维护实例集合,直接求和

如果需要保留实例自身的累计逻辑,也可以通过静态集合保存所有实例,在getTotalCost()中遍历求和:

import java.util.ArrayList;
import java.util.List;

public class Second {
    private static List<Second> instances = new ArrayList<>();
    private int totalPrice = 0;
    
    // 构造时自动加入集合
    public Second() {
        instances.add(this);
    }
    
    public void add(String name, int price, int count) {
        totalPrice += count * price;
    }

    public static int getTotalCost() {
        return instances.stream().mapToInt(Second::getTotalPrice).sum();
    }
    
    public int getTotalPrice() {
        return totalPrice;
    }
}

第一种方案更贴合你原有代码逻辑,修改成本最低。

内容的提问来源于stack exchange,提问作者Sergei Kondrashkin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 22:35:22