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
相关产品推荐
相关产品推荐

