如何一次又一次地使用相同的迭代器?

编程入门 行业动态 更新时间:2024-10-26 23:25:49
本文介绍了如何一次又一次地使用相同的迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出下一个代码:

//这是某个大方法的一部分//

ArrayList< String> players = this.m_maze.getPlayers(); //将第一个节点定义为人类玩家,并从列表中弹出他 //其余节点是计算机端 Iterator< ;字符串> iterator = players.iterator(); //人类边字符串humanPlayer = iterator.next(); //控制器 - 在玩家之间开始游戏,至少有两名玩家玩而(this.m_rounds> 0) { String [] choices = this.m_view.getChoiceFromUser(); int usersChoice = Integer.parseInt(choices [0]); 开关(usersChoice) {案例1://然后用户选择保留 { } 案例2://然后采取下一步 { //让用户移动 this.m_maze = this.m_model.makeSomeMove(选择[1],humanPlayer,TRUE); //打印迷宫以进行可视化 this.m_view.drawMaze(m_maze); //控制器 - 减少当前游戏的当前回合数 this.m_rounds--; } 案例31://然后用户要求最近的宝贝 { //稍后在上放一些代码} 案例32://然后用户要求最近的房间 { //稍后在放置一些代码} } //结束开关盒 } //结束时

( 1)。每次调用 makeSomeMove 后,我如何在 humanPlayer 中放置ArrayList的第一个元素? / p>

(2)。是否可以重用迭代器?因为我使用 hasnext()和 next() ...?

非常感谢 Ron

解决方案

如果你想要要重用迭代器,你必须重新初始化它。

你必须执行 Iterator< String> iterator = players.iterator(); 每当你想重用迭代器时。

Given the next code :

// this is a part of some large method //

ArrayList<String> players = this.m_maze.getPlayers(); // define the first node to be the human player , and pop him from the list // the rest of the nodes are the computer side Iterator<String> iterator = players.iterator(); // human side String humanPlayer = iterator.next(); // controller - start a game between the players , at least two players are playing while (this.m_rounds > 0) { String[] choices = this.m_view.getChoiceFromUser(); int usersChoice = Integer.parseInt(choices[0]); switch (usersChoice) { case 1: // then user chose to stay put { } case 2: // then take the next step { // let the user make his move this.m_maze = this.m_model.makeSomeMove(choices[1],humanPlayer,true); // print out the maze for visualization this.m_view.drawMaze(m_maze); // controller - reduce the number of current rounds for the current game this.m_rounds--; } case 31: // then user asked for the closest treasure { // put some code here later on } case 32: // then user asked for the nearest room { // put some code here later on } } // end switch case } // end while

(1).How can I place in humanPlayer the first element of the ArrayList after each time that I invoke makeSomeMove ?

(2).Is it possible to reuse an iterator ? since I use the hasnext() and next() ... ?

Many thanks Ron

解决方案

If you want to reuse the iterator, you have to re-initialise it.

You have to execute Iterator<String> iterator = players.iterator(); whenever you want to reuse the iterator.

更多推荐

如何一次又一次地使用相同的迭代器?

本文发布于:2023-11-27 23:54:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640121.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:迭代

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!