2012-02-04 74 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