【发布时间】:2014-10-29 09:26:54
【问题描述】:
这是本书的修改示例,Head First Java。这是一种战舰游戏,其中一个 3 元素阵列被用作战舰。用户必须猜测这 3 个位置。目前,我已将船舶位置的值硬编码为 2、3、4。当用户猜到正确的位置时,“Hit”被打印出来。如果不是,则打印“Miss”。如果用户猜到所有 3 个位置,则打印“Kill”。但我有一个问题。目前,如果用户多次进入同一个位置,它仍然会命中。我试图通过将已经被命中的变量(int cell)的值更改为“-1”来解决这个问题。但由于某种原因,这也没有解决它。请告诉我我做错了什么。
public class Game {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] location = {2,3,4};
SimpleDotCom firstGame = new SimpleDotCom();
firstGame.setLocation(location);
firstGame.checkYourself("2");
firstGame.checkYourself("2");
//firstGame.checkYourself("2");
}
}
public class SimpleDotCom {
int [] loc = null;
int numOfHits = 0;
void setLocation (int [] cellLocation){
loc = cellLocation;
}
void checkYourself(String userGuess){
int guess = Integer.parseInt(userGuess);
String result = "Miss";
for(int cell:loc){
if (guess == cell){
result = "Hit";
numOfHits++;
cell = -1;
break;
}
if (numOfHits==loc.length){
result = "Kill";
}
}
System.out.print("Result: " + result);
System.out.println(" ** Num of Hits: " + numOfHits);
}
}
【问题讨论】:
-
程序很短很简单,你调试过吗?
-
没有。我已经忘记如何调试了。现在用谷歌搜索。
-
如果打印了“Hit”,您必须从数组中删除该元素。
-
我没有删除那个元素,我只是将它的值更改为用户不会猜到的值(在本例中为 -1)。是一样的吧?
-
你们真的很快。谢谢大家。
标签: java