2012-02-04 91 views
0

考慮以下幾點:重新初始化不起作用

// get the list of the players , in order to start the game 
    ArrayList<String> players = this.m_maze.getPlayers(); 
    // human side 
    String humanPlayer = iterator.next(); 
    String computerPlayer = null; 
    // define iterator for the players 

    Iterator<String> iterator = players.iterator();  
    boolean humanSide = true ,computerSide = false; // assume the human player is starting the game 


    // controller - start a game between the players , at least two players are playing 

    while (this.m_rounds > 0) 
    { 

     if (humanSide == false && computerSide == true) // then this is the turn of the human side 
     { 
      if (iterator.hasNext() == false) 
      { 
       // reinitialize the iterator 
       Iterator<String> iterator = players.iterator(); 

      } 
      while (iterator.hasNext()) 


         // more code 

我嘗試重用迭代器,但我得到一個「複製局部變量的迭代器」編譯錯誤。我怎樣才能重用該迭代器? 謝謝你,羅恩

編輯:

  if (iterator.hasNext() == false) 
      { 
       // reinitialize the iterator 
       iterator = players.iterator(); 

      } 
      while (iterator.hasNext()) 
      { 
       computerPlayer = iterator.next(); 

       // computer decides what would be his next move , between 1 - 3 
+1

這聽起來像你真正想要做的是循環迭代。你有沒有考慮過使用循環數據結構? – 2012-02-04 06:30:40

+0

這是一個非常好的主意,我會考慮到這一點,謝謝! – ron 2012-02-04 06:33:02

回答

3

不要重新聲明變量;只是分配它。

if (iterator.hasNext() == false) { 
    iterator = players.iterator(); 
} 

您應該小心嵌套循環行爲。你真正的意圖是有以下幾個塊嗎

while (iterator.hasNext()) { ... } 

實際檢查這個條件嗎?

while (iterator.hasNext() && (this.m_rounds > 0)) { ... } 
1

你已經在你的循環放Iterator<String> iterator = players.iterator();

所以每次它試圖創建名稱爲iterator的變量。

只要把它的聲明圈外的......像

Iterator<String> iterator;  //here **** 
while (this.m_rounds > 0) 
    { 

    if (humanSide == false && computerSide == true) // then this is the turn of the human side 
    { 
     if (iterator.hasNext() == false) 
     { 
      // reinitialize the iterator 
      iterator = players.iterator(); 

     } 
     while (iterator.hasNext()) 
+0

這將拋出'NullPointerException',因爲在'hasNext()'的調用之前'iterator'沒有被賦值。 – cheeken 2012-02-04 06:30:53

+0

@cheeken如果是這樣的話,那麼它會根據他的代碼拋出異常bcoz,他在hasNext()之前沒有賦值給iterator() – gprathour 2012-02-04 06:33:09

0

奧凱只是刪除了Iterator<String>,意思是,重複使用迭代器時,只寫:iterator = players.iterator();

謝謝大家!

1

我覺得谷歌番石榴幾乎有你想要的Iterators#cycle

使用方法如下:

Iterator<String> iterator = Iterators.cycle(players.iterator()); 

...你將永遠不會用完的球員。

1

不要使用像這樣的迭代器,它可以搞砸了,只是做舊的方式,我的意思是使用着名的先生Iterator「我」。此外,代碼看起來更明智。

while(m_rounds > 0){ 

     if(i == players.size()) { 
      i = 0; 
     } 

     currentPlayer = players.get(i); 

     //Do what you want to do with the current player... 

     ... 

     //Next 
     i++; 


    } 

一個小小的建議,你真的需要這兩個標誌,我指的是humanSide和computerSide?不會只用一個就足夠了?你的if-else塊看起來會更簡單明瞭:

if(humanSide) { 

    //Hope this move wouldn't crush your logic. 

} else { 

    //Algorithm based awesome move. 

} 
+0

你是對的。我會去做! 10X。 – ron 2012-02-05 08:29:17