這是來自Head First Java一書的修改示例。這是一種戰艦類遊戲,其中一個3元素陣列被用作戰艦。用戶必須猜測這3個位置。目前,我已經將船位的值硬編碼爲2,3,4。當用戶猜測正確的位置時打印出「Hit」。如果沒有,則打印「小姐」。如果用戶猜測全部3個位置,則打印「殺死」。但我有一個問題。目前,如果用戶多次進入同一地點,它仍然會受到打擊。我試圖通過將已被命中的變量(int cell)的值更改爲「-1」來解決此問題。但由於某種原因,這並沒有解決它。請告訴我我做錯了什麼。增強for循環的一些問題 - SimpleDotCom
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);
}
}
程序非常簡短,你有沒有試過調試它? – nogard 2014-09-04 14:57:28
不,我忘記了如何調試。現在使用Google搜索。 – MJB 2014-09-04 14:58:29
如果打印「打印」,則必須從陣列中刪除該元素。 – Jens 2014-09-04 15:00:53