头 第一个Java书战舰游戏



我正在阅读"Head First Java"一书,我在战舰游戏(简单版本)的第5章中遇到了问题。我知道这本书的代码不起作用,我尝试自己修复它,但它仍然不起作用。

所以试图谷歌它,我在这个网站上找到了一些帖子,但我仍然有一个问题。游戏无法正常工作。

如果玩家输入任何随机数,输出总是被"命中"......

这是代码的最新版本:

网络通信类:

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;
}
}

网络游戏类:

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");
}
}
}
}

我真的很感激得到一个详细且易于理解的答案,因为我被困住了,几天来我无法继续阅读这本书。

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";
}

如果你没有杀死对手的船只,那么你要么错过所有船只,要么击中一艘船只。

我猜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。

最新更新