2014-09-04 92 views
1

這是來自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); 
} 

    } 
+0

程序非常簡短,你有沒有試過調試它? – nogard 2014-09-04 14:57:28

+0

不,我忘記了如何調試。現在使用Google搜索。 – MJB 2014-09-04 14:58:29

+0

如果打印「打印」,則必須從陣列中刪除該元素。 – Jens 2014-09-04 15:00:53

回答

3

當您循環使用loc時,您會得到每個位置的int cell。問題是該變量沒有任何連接到數組,它只是一個副本。如果你改變它,原始數組什麼都不會發生。我建議使用傳統的for(;;)循環播放loc,並使用循環邏輯中的當前數組索引將右側的「單元格」設置爲-1。

+0

謝謝,我不知道。 – MJB 2014-09-04 15:10:24

1

因爲您正在爲本地變量賦值-1。在陣列不更新實際

for(int cell:loc){ // cell is local copy of element in array is you have array of primitive int 
    if (guess == cell){ 
     result = "Hit"; 
     numOfHits++; 
     cell = -1; 
     break; 
    } 
    if (numOfHits==loc.length){ 
     result = "Kill"; 
     } 
    } 

可以使用傳統的for循環這個或使用List其具有用於添加刪除元素的方法。

+0

謝謝,明白了。 – MJB 2014-09-04 15:09:41

0

您需要以正確的索引更新數組,而不是簡單地更改cell變量的值,該變量僅引用當前迭代狀態下的數組元素。

您應該使用傳統的for循環,因爲您無法從增強for循環獲取索引。

for (int i = 0; i < loc.length; i++) { 
    //code... 

    loc[i] = -1; //instead of cell = -1; 
} 
+0

謝謝。這固定了它。 – MJB 2014-09-04 15:10:43

+0

不要忘記接受答案;) – plalx 2014-09-04 16:16:45

+0

接受第一個正確的答案:) – MJB 2014-09-04 16:26:12