Java history数组仅存储打印最新存入值的故障排查
故障定位:history数组仅存储最后一题记录
问题描述
无法确定是数组本身逻辑存在故障,还是数组打印代码出现问题。当前程序运行后history数组仅保存最后一次存入的题目内容,打印时无法展示全部历史题目记录,问题范围在下方三段代码内,其中后两段代码属于同一个类。
涉事代码
主流程循环代码
/*This is the main class that prints out everything */ //Start the problems loop for (int i = 0; i < session.getNumProb(); i++) { //Set random values for factors cards.setFactors(); //Create problems cards.setProb(session); //Determine correct/incorrect answer, update running score cards.setResponse(session); //Add the problem to the history array session.setHistory(cards); } //Set score percentage session.setScorePct(); //Print out summary session.prtSummary(); //Print out history array and outro session.prtHistoryAndOutro();
history写入方法
/* This sets the history based on questions asked */ //setHistory public void setHistory(Cards c) { for (int i = 0; i < numProb; i++) { history[i] = c.getA() + oper + c.getB() + " = " + c.getResponse() + ", " + c.getCorInc() + ", correct answer is " + c.getC(); System.out.println(); } }
history打印方法
/* This prints out the history array */ //prtHistoryAndOutro public void prtHistoryAndOutro() { System.out.println("Problems"); for (int i = 0; i < numProb; i++) { System.out.println(history[i]); } System.out.println(); System.out.println(); System.out.println("Thank you for using the 3312 FlashCard System, " + name + "."); System.out.println("Come back and play again real soon!"); }
故障原因
打印逻辑没有任何问题,错误完全出在setHistory的实现:
- 主循环每完成1道题就调用1次
setHistory,预期是每次往数组里追加1条新记录 - 但当前
setHistory每次调用都会遍历整个数组的所有下标,把所有位置的内容全部覆盖成当前传入的单道题信息 - 流程表现为:答完第1题,数组所有位置存第1题;答完第2题,数组所有位置被覆盖为第2题;直到答完最后一题,数组全量被最后一题内容覆盖,最终打印自然只能看到最后一题的记录。
- 额外冗余:
setHistory内的System.out.println()无输出内容,只会打印空行,可以直接删除。
修复方法
- 在Session类中新增一个整型成员变量记录历史写入位置,初始化值为0:
private int historyCursor = 0;
- 重写
setHistory方法,移除内部全数组遍历逻辑,每次只写入当前游标对应的位置,写完游标自增:
public void setHistory(Cards c) { history[historyCursor] = c.getA() + oper + c.getB() + " = " + c.getResponse() + ", " + c.getCorInc() + ", correct answer is " + c.getC(); historyCursor++; }
- 每次开启新的答题会话、初始化题目数量时,记得把
historyCursor重置为0,避免数组下标越界。
内容的提问来源于stack exchange,提问作者Naruaharu
相关产品推荐
相关产品推荐

