如何将Dice类生成的随机数作为变量在其他Java类中使用?
解决方案
1. 重构Dice类
让Dice类专注于生成随机数的核心职责,不再直接处理弹窗,通过方法返回生成的数值,供其他类调用:
package stockGame; import java.util.Random; // 仅负责生成1-12的随机数 public class Dice { private Random random; public Dice() { random = new Random(); } // 生成并返回1-12的随机数 public int roll() { return random.nextInt(12) + 1; } }
2. 封装游戏逻辑类
创建GameLogic类,负责处理用户选择、骰子结果比较、胜负判定及结果输出,实现逻辑与UI的分离:
package stockGame; import javax.swing.JOptionPane; // 处理游戏核心逻辑:用户选择解析、胜负判断、结果展示 public class GameLogic { private Dice dice; public GameLogic() { dice = new Dice(); } // 根据用户选择判定胜负并弹出结果 public void runGame(int userOption) { int diceNum = dice.roll(); String resultMsg = getResultMessage(userOption, diceNum); // 先提示电脑生成的随机数 JOptionPane.showMessageDialog(null, "The Computer picked " + diceNum); // 再展示胜负结果 JOptionPane.showMessageDialog(null, resultMsg, "Game Result", JOptionPane.INFORMATION_MESSAGE); } // 构建胜负结果文本 private String getResultMessage(int userOption, int diceNum) { String choiceText; boolean isWin = false; switch(userOption) { case 1: choiceText = "trade less than £6"; isWin = diceNum < 6; break; case 2: choiceText = "trade more than £6"; isWin = diceNum > 6; break; case 3: choiceText = "trade exactly £6"; isWin = diceNum == 6; break; default: return "Invalid choice! Please select 1, 2 or 3."; } String outcome = isWin ? "you win!" : "you lose!"; return String.format("You chose to %s and the computer rolled %d, so %s", choiceText, diceNum, outcome); } }
3. 主入口类示例
在主类中完成用户输入获取,并调用游戏逻辑类启动流程:
package stockGame; import javax.swing.JOptionPane; public class StockGameMain { public static void main(String[] args) { // 获取用户选择 String input = JOptionPane.showInputDialog(null, "Choose your trade option:\n1. Less than £6\n2. More than £6\n3. Exactly £6"); if (input == null) return; // 用户取消输入 int userOption; try { userOption = Integer.parseInt(input); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid input! Please enter a number between 1-3."); return; } // 启动游戏逻辑 GameLogic game = new GameLogic(); game.runGame(userOption); } }
改动说明
- 职责分离:Dice类只做随机数生成,GameLogic类处理业务逻辑,主类负责用户交互,每个类职责单一,便于维护和复用。
- 解决数值传递问题:通过Dice的
roll()方法返回随机数,其他类可直接获取该值用于判断。 - 代码拆分:将消息构建逻辑抽成独立方法,避免代码堆积,提升可读性。
内容的提问来源于stack exchange,提问作者Lisa Wilson
相关产品推荐
相关产品推荐

