Java开发Mäxchen游戏时如何将result变量传递到新类
问题描述
- 开发目标:复刻德国饮酒游戏「Mäxchen」的Java程序
- 现存问题:无法将
rollDice()方法内部的result变量传递给其他独立类,存在类间变量访问障碍 - 运行环境:Eclipse、JDK18、Windows 10
- 问题相关原始代码:
import java.util.Random; import java.util.*; public class MäxchenDiceRoll { public void rollDice() { //beginning of user input for amount of players Scanner playerAmountInput = new Scanner(System.in); System.out.println("Enter amount of players \n"); String playerAmount = playerAmountInput.nextLine(); System.out.println("Amount of players are: " + playerAmount); //end of user input for amount of players Random ran = new Random(); int die1; int die2; die1 = ran.nextInt(6)+1; die2 = ran.nextInt(6)+1; int result; if(die1>die2) { result = (die1*10) + die2; System.out.println("The result is: " + result); } else if(die2>die1) { result = (die2*10) + die1; //System.out.println("The result is: " + result); } else if(die1==die2) { result = (die1*10) + die2; System.out.println("The result is: " + result); } } }
实现方案
问题核心原因:result是rollDice()方法内的局部变量,作用域仅局限在当前方法内部,方法执行结束后变量就会被回收,外部类天然无法直接访问。可以根据业务场景选以下两种常用实现:
方案1:修改方法返回值(推荐,耦合度最低)
直接把rollDice()的返回值类型从void改为int,方法执行完成后把计算出的result作为返回值返回,调用方直接接收返回值即可使用,不需要额外维护变量状态。
修改后的MäxchenDiceRoll类代码参考:
import java.util.Random; import java.util.Scanner; public class MäxchenDiceRoll { public int rollDice() { // 建议把玩家数量输入逻辑从掷骰子方法里拆出去,单独做初始化方法,避免每次掷骰都触发输入 Random ran = new Random(); int die1 = ran.nextInt(6) + 1; int die2 = ran.nextInt(6) + 1; int result; if(die1 >= die2) { result = die1 * 10 + die2; } else { result = die2 * 10 + die1; } System.out.println("The result is: " + result); // 核心:返回计算结果 return result; } }
其他类调用示例:
public class GameMain { public static void main(String[] args) { MäxchenDiceRoll diceRoller = new MäxchenDiceRoll(); // 直接调用方法拿到掷骰结果 int rollResult = diceRoller.rollDice(); // 后续业务逻辑直接用rollResult即可 System.out.println("其他类拿到的掷骰结果:" + rollResult); } }
方案2:将result设为类成员变量,提供访问接口
如果需要在同一个MäxchenDiceRoll实例的多个方法里复用掷骰结果,可以把result提升为类的私有成员变量,掷骰完成后给成员变量赋值,对外提供公共的getter方法供外部类取值。
代码参考:
import java.util.Random; public class MäxchenDiceRoll { // 私有成员变量存储掷骰结果 private int result; public void rollDice() { Random ran = new Random(); int die1 = ran.nextInt(6) + 1; int die2 = ran.nextInt(6) + 1; if(die1 >= die2) { result = die1 * 10 + die2; } else { result = die2 * 10 + die1; } System.out.println("The result is: " + result); } // 对外提供get方法获取结果 public int getResult() { return result; } }
其他类调用示例:
public class GameMain { public static void main(String[] args) { MäxchenDiceRoll diceRoller = new MäxchenDiceRoll(); // 先执行掷骰逻辑 diceRoller.rollDice(); // 调用getter拿到结果 int rollResult = diceRoller.getResult(); System.out.println("其他类拿到的掷骰结果:" + rollResult); } }
注意:不要为了方便直接把
result设为public static修饰的全局变量,这种写法会严重破坏类的封装性,多人轮次掷骰时很容易出现值被覆盖的bug。
内容的提问来源于stack exchange,提问作者PythonSux
相关产品推荐
相关产品推荐

