我正在尝试使用ArrayList构建一个二十一点纸牌游戏。我无法弄清楚向所有玩家发放单张牌的逻辑 - 我认为我的问题必须在使用迭代器方面做得更多......
问题出在GameRunner的//交易卡部分。我知道我没有正确使用itr为ArrayList中的每个玩家分配一张新牌。
import java.util.*;
public class GameRunner {
public static void main(String[] args) {
int numDecks = Integer.parseInt(args[0]);;
int numPlayers = Integer.parseInt(args[1]);
String pName;
//init
Scanner sc = new Scanner(System.in);
Deck gameDeck = new Deck(numDecks, true);
List<Player> players = new ArrayList<>();
players.add(new Player("Dealer"));
//create players
do{
System.out.print("Enter an name of a player: ");
pName = sc.next();
players.add(new Player(pName));
numPlayers--;
}while( numPlayers > 0);
System.out.println(players.toString());
//deal cards
ListIterator<Player> itr = (ListIterator<Player>) players.iterator();
while (itr.hasNext()){
itr.drawCard(gameDeck.dealNextCard());
}
}//end main
}//end GameRunner class
...
来自玩家类的:
public boolean drawCard(Card aCard){
//print error if player is already at the card max
if(this.numCards == MAX_CARDS){
System.err.printf("%s's hand already has " + MAX_CARDS +
"cannot add another card\n", this.name);
System.exit(1);
}
//add new card in the next slot and increment the number of cards
this.hand[this.numCards] = aCard;
this.numCards++;
return (this.getHandSum() <= 21);
}
来自甲板课
public Card dealNextCard(){
if (numCards == 0){
System.err.print("Too Few Cards to Deal another card");
System.exit(1);
}
this.numCards--;
return mCards.pop();
}
答案 0 :(得分:2)
在使用迭代器的部分中,使用以下命令:
// deal cards
for (Player p : players) {
p.drawCard(gameDeck.dealNextCard());
}
此for (Player p : players)
称为增强型循环,有时也称为 for-each循环。它循环遍历Iterable
对象中的每个项目。 Iterable
对象是实现Iterable
接口的对象。
players
,类型为ArrayList<Player>
,实现Iterable<Player>
接口,因此可以在增强的for循环中使用。
上面使用的增强的for循环等同于以下内容:
Iterator<Player> iter = players.iterator();
while (iter.hasNext()) {
Player p = iter.next(); // this statement is what your code was missing
p.drawCard(gameDeck.dealNextCard());
}
以下是有关增强型for循环的Oracle教程的链接:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
希望这有帮助!