Java开发《谁想成为百万富翁》游戏跨方法调用getUser()返回null求助
问题根因
- 你在
main方法中实例化了第一个User对象getUserMethods,调用storeUser()完成了用户名赋值,这个对象的user字段确实有值 - 但你在
GameMethods类的reviewUserInput方法中,又重新new User()创建了第二个完全独立的User实例,这个新实例从来没有调用过storeUser()方法,它的私有user字段默认就是null,自然调用getUser()返回空值 - 两个
User实例是完全独立的内存对象,字段值不共享,所以你之前存的值在第二个对象里读不到
修复方案
- 首先修改
GameMethods类,不要在方法内部新建User对象,而是通过构造方法传入main中已经初始化好的那个User实例:
public class GameMethods { int count = 0; String name = ""; int score = 0; // 新增成员变量持有外部传入的User实例 private User user; // 修改构造方法,接收User实例 public GameMethods(User user) { this.user = user; } public void reviewUserInput(String input, String answer, HashMap <Integer, LifeLines> lifelines) { // 删除这行代码,不要新建User实例:User getUser = new User(); GameMethods getGameMethods = new GameMethods(); boolean loop = true; // 原有其他逻辑不变,所有之前用到getUser的地方,全部替换成this.user if (input.equalsIgnoreCase("x")) { System.exit(0); } else if (input.equalsIgnoreCase("l")) { input = getGameMethods.hasLifelines(lifelines, answer); } else if (!input.equalsIgnoreCase("a") && !input.equalsIgnoreCase("b") && !input.equalsIgnoreCase("c") && !input.equalsIgnoreCase("d")) { while(loop) { System.out.println("Invalid Input try again!!"); input = getGameMethods.getUserInput(); if (input.equalsIgnoreCase("a") || input.equalsIgnoreCase("b") || input.equalsIgnoreCase("c") || input.equalsIgnoreCase("d") || input.equalsIgnoreCase("l") || input.equalsIgnoreCase("x")) { loop = false; if (input.equalsIgnoreCase("x")) { System.exit(0); } else if (input.equalsIgnoreCase("l")) { input = getGameMethods.hasLifelines(lifelines, answer); } } } } if (input.equalsIgnoreCase(answer)) { count++; System.out.println("Correct answer!!!"); user.setUserEarnings(count); } else if (!input.equalsIgnoreCase(answer)) { count-=5; System.out.println("Unfortunately this answer is wrong"); user.setUserEarnings(count); System.out.println("Thank you for playing"); user.storeUserHighscore(name, score); System.exit(0); } } }
- 修改main方法中
GameMethods的实例化代码,传入已经完成storeUser的User对象:
public static void main(String[] args) { String answer; String userInput; HashMap <Integer, LifeLines> lifelines = new HashMap <> (); lifelines.put(0, lifeLine); lifelines.put(1, lifeLine); lifelines.put(2, lifeLine); InputOutput getInputMethods = new InputOutput(); User getUserMethods = new User(); getInputMethods.readIntroduction(); getInputMethods.clearBuffer(); getUserMethods.storeUser(); // 实例化GameMethods的时候传入已经初始化好的User对象 GameMethods getGameMethods = new GameMethods(getUserMethods); for(int counter = 0; counter < 16; counter++) { getInputMethods.readQuestion(); getInputMethods.readA(); getInputMethods.readB(); getInputMethods.readC(); getInputMethods.readD(); answer = getInputMethods.readAnswer(); userInput = getGameMethods.getUserInput(); getGameMethods.reviewUserInput(userInput, answer, lifelines); } }
修复后所有逻辑复用同一个User实例,之前存储的用户名就可以正常读取了。
内容的提问来源于stack exchange,提问作者Justformaddenpurposes
相关产品推荐
相关产品推荐

