[英]Head First Java book battleship game
我正在阅读《 Head First Java》一书,在第5章中,通过战舰游戏(简单版)遇到了这个问题。 我知道这本书的代码不起作用,我尝试对其进行自我修复,但是仍然没有用。
所以尝试用谷歌搜索它,我在这个网站上找到了一些帖子,但是我仍然有问题。 游戏无法正常运行。
如果玩家输入任何随机数,则输出始终为“命中” ...
这是代码的最新版本:
DotCom类:
public class DotCom {
private ArrayList<String> locationCells = new ArrayList<>();
public void setlocationCells(int[] loc) {
if (loc != null)
for (int val : loc)
locationCells.add(String.valueOf(val));
}
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
}
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
System.out.println(result);
return result;
}
}
DotComGame类:
public class DotComGame {
public static void main(String[] args) {
int guessingTimes = 0;
DotCom dot = new DotCom();
GameHelperrr helper = new GameHelperrr();
int randomNum = (int) (Math.random() * 5);
int[] locations = { randomNum, randomNum + 1, randomNum + 2 };
dot.setlocationCells(locations);
boolean isAlive = true;
while (isAlive == true) {
String guess = helper.getUserInput("Enter a number");
String result = dot.checkYourself(guess);
guessingTimes++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + guessingTimes + " guesses");
}
}
}
}
希望得到详细且可以理解的答案,我非常感激,因为我被困住了,而且现在几天都无法继续着这本书。
我猜想checkYourself-Method必须是这样的:
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if(index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
}else {
result = "hit";
}
}
System.out.println(result);
return result;
}
在当前形式下,ArrayList永远不会为空,因为您插入了3个值,但只有在用户输入位于列表中时才删除1,因此.isEmpty()永远不会为TRUE。
int index = locationCells.indexOf(userInput);
如果该元素在集合中不存在,则此方法将返回-1
。
因此,如果您错过了,它将不会达到以下条件:
if (index >= 0) {
locationCells.remove(index);
}
这个集合中仍然有元素,因为您没有删除任何东西...
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
因此,如果错过了,结果仍然显示为“命中”。
尝试以下方法:
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = index == -1 ? "miss" : "hit";
}
如果您没有杀死对手的战舰,那么您要么错过所有战舰,要么击中一艘战舰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.