【发布时间】:2019-08-26 15:14:03
【问题描述】:
我正在阅读“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");
}
}
}
}
我真的很感激能得到一个详细且易于理解的答案,因为我被困住了,几天都无法继续阅读这本书。
【问题讨论】:
-
什么版本的“Head First Java”?那是一本比较老的书。如果它没有假设 JDK 8 或更高版本,请小心。