Java游戏类调用带参数方法报‘Identifier expected’错误的解决求助
问题解决:Java方法调用的"Identifier expected"错误
错误原因分析
- 方法调用语法错误:在
startGame()里调用resetDiceCup( int doublets, int numOfDoublets);时,错误地在参数前添加了类型声明int。Java中调用方法只需传入实际参数(变量或字面量),类型声明是方法定义阶段的语法,调用时不能使用。 - 方法参数设计逻辑错误:
resetDiceCup()的参数doublets和numOfDoublets是局部变量,方法内将其赋值为0只会修改局部值,无法影响游戏的全局状态——你需要重置的应该是Game类的成员变量,而非方法参数。
修正步骤
1. 声明Game类的成员变量
将需要重置的状态变量定义为类的成员(放在方法外):
public class Game{ // 游戏状态成员变量 private int[] result; private int sum; private int doublets; private int numOfDoublets; private int sumWithDoublets; private int numOfDices; // 需提前设置骰子数量,比如通过构造方法或其他逻辑 private Player[] player; // 后续方法... }
2. 修改resetDiceCup为无参方法
去掉不必要的参数,直接重置类的成员变量:
// 重置骰盅状态 public void resetDiceCup() { result = new int[numOfDices]; sum = 0; doublets = 0; numOfDoublets = 0; sumWithDoublets = 0; }
3. 修正startGame中的方法调用
直接调用无参的resetDiceCup():
public void startGame() { resetDiceCup(); // 正确调用无参重置方法 System.out.println("Willkommen zu diesem Würfelspiel. Los geht´s!"); String[] playerNames = Print.multipleAnswers("Please insert the name of a player."); player = new Player[playerNames.length]; for (int i = 0; i < playerNames.length; i++) { player[i] = new Player(playerNames[i]); } }
额外说明
如果numOfDices是由玩家选择的动态值,需要在调用resetDiceCup()之前完成赋值,比如可以在startGame()开头添加骰子数量的获取逻辑,或者将numOfDices作为resetDiceCup()的参数传入(此时调用时传入实际数值即可,无需加类型声明)。
内容的提问来源于stack exchange,提问作者Alice333
相关产品推荐
相关产品推荐

