这是 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);
}
}
最佳答案
当您遍历 loc
时,您会为每个位置获得一个 int cell
。问题是该变量与数组没有任何联系,它只是一个副本。如果您更改它,原始数组将不会发生任何变化。我建议使用传统的 for(;;)
遍历 loc
并使用循环逻辑中的当前数组索引将正确的“单元格”设置为 -1。
关于java - 增强的 for loop-SimpleDotCom 的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25668707/