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

Java中添加Player实例时playerCount静态计数始终为0的问题求助

玩家计数始终为0的修复方案

问题核心:你定义了静态变量playerCount,但没有在创建玩家实例时对它执行递增操作,所以这个数值一直停留在初始的0,不会随新玩家添加变化。

修改后的代码:

public class Player {

    String name;
    static int playerCount = 0;
    
    Player(String name) {
        this.name = name;
        // 新增计数递增逻辑
        playerCount++;
        System.out.println("Player " + name + " added to the team!");
    }
            
    public static void main(String[] args) {
        
        Player one = new Player("x");
        System.out.println("the count now is " + playerCount);
        
        Player two = new Player("y");
        System.out.println("the count now is " + playerCount);
        
        Player three = new Player("z");
        System.out.println("the count now is " + playerCount);
    }
}

说明:

  • 在Player构造函数中加入playerCount++,每次创建新玩家对象时,静态计数就会自动加1
  • 静态变量playerCount属于Player类本身,所有玩家实例共享这个值,能正确累计总玩家数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:35:24