换一种能保证合法性的改法
时间: 2024-03-04 13:48:40 浏览: 16
可以在程序中增加一个函数,用于检查用户输入的成语是否合法。例如:
```
public boolean isValidChengYu(String chengYu) {
// 检查成语是否符合成语规范
if (chengYu.length() != 4) {
return false;
}
// 检查成语是否在成语列表中
for (ChengYu cy : fullChengYuList) {
if (cy.getChengYu().equals(chengYu)) {
return true;
}
}
return false;
}
```
然后,在程序中修改如下代码:
```
if (isValidChengYu(answer) && answer.startsWith(currentChengYu.getChengYu().substring(currentChengYu.getChengYu().length() - 1))) {
System.out.println("我接的成语为:" + answer);
currentChengYu = new ChengYu(answer);
} else {
currentChengYu = null;
System.out.println("无法继续接龙");
break;
}
```
这样,程序就会在接龙时检查用户输入的成语是否合法,并且保证了接龙出来的成语都是符合成语规范的。