修改代码,使startGame方法运行到执行getHinder()后回到for(;success;) public void startGame() { Scanner scanner = new Scanner(System.in); while (true) { System.out.println("请选择游戏模式(1-娱乐模式,2-困难模式,0-退出):"); int mode = scanner.nextInt(); if (mode == 0) { break; } List<ChengYu> chengYuList; if (mode == 1) { chengYuList = commonChengYuList; } else { chengYuList = fullChengYuList; } Collections.shuffle(chengYuList); // 打乱顺序 int score = 0; boolean success = true; //随机抽取一个成语 Random random = new Random(); int index = random.nextInt(chengYuList.size()); ChengYu cy = chengYuList.get(index); String currentIdiom = cy.getChengYu(); for(;success;) { System.out.println(hintCount); for (ChengYu chengYu : commonChengYuList) if(chengYu.getChengYu().startsWith((currentIdiom.substring(currentIdiom.length() - 1)))) break; System.out.println("请回答以下成语的下一个成语:" + currentIdiom + "(难度:" + cy.getDifficultyLevel().getName() + ")"); String answer = scanner.next(); if (!cy.isCorrectAnswer(answer,commonChengYuList)) { System.out.println("回答错误!"); success = false; getHint(currentIdiom); } else { score++; } if (success) { System.out.println("恭喜您回答正确,得分:" + score); for (ChengYu nextChengYu : fullChengYuList) if(nextChengYu.getChengYu().startsWith((answer.substring(answer.length() - 1)))) currentIdiom=nextChengYu.getChengYu(); } } } scanner.close(); } //给予用户最多3次提示的机会 private int maxHintCount=3; // 最大提示次数 private int hintCount=0; // 当前提示次数 public String getHint(String currentIdiom) { if (hintCount >= maxHintCount) { System.out.println("提示次数已全部用完,请重新开始游戏!"); hintCount=0; return null; // 已经用完所有提示次数,返回null } for (ChengYu idiom : fullChengYuList) { if(hintCount<maxHintCount) { String reminder=idiom.getChengYu(); if (reminder.startsWith(currentIdiom.substring(currentIdiom.length() - 1))) { System.out.println("提示:"+reminder); hintCount++; break; } } } return null; }
时间: 2024-03-03 17:51:04 浏览: 162
在 `getHint()` 方法中,当提示次数已经用完时,需要将 `hintCount` 重置为 0,否则在下一轮游戏时,提示次数将被累加上一轮游戏中剩余的提示次数,从而导致提示次数异常。修改后的代码如下:
```java
public String getHint(String currentIdiom) {
if (hintCount >= maxHintCount) {
System.out.println("提示次数已全部用完,请重新开始游戏!");
int hintCount = 0; // 重置 hintCount 为 0
return null; // 已经用完所有提示次数,返回null
}
for (ChengYu idiom : fullChengYuList) {
if(hintCount<maxHintCount) {
String reminder=idiom.getChengYu();
if (reminder.startsWith(currentIdiom.substring(currentIdiom.length() - 1))) {
System.out.println("提示:"+reminder);
hintCount++;
break;
}
}
}
return null;
}
```
另外,在 `startGame()` 方法中,如果用户回答错误时,需要在调用 `getHint()` 方法后重新进入循环判断。修改后的代码如下:
```java
if (!cy.isCorrectAnswer(answer,commonChengYuList)) {
System.out.println("回答错误!");
success = false;
getHint(currentIdiom);
continue; // 重新进入循环判断
} else {
score++;
}
```
这样,当用户回答错误时,程序会调用 `getHint()` 方法给予提示,并重新进入循环判断,直到用户回答正确或者提示次数用完为止。
阅读全文