gpt4 book ai didi

java - 向玩家数组列表发一张牌

转载 作者:行者123 更新时间:2023-11-30 03:48:20 25 4
gpt4 key购买 nike

我正在尝试使用 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);
}

来自 Deck 类

    public Card dealNextCard(){ 
if (numCards == 0){
System.err.print("Too Few Cards to Deal another card");
System.exit(1);
}
this.numCards--;
return mCards.pop();
}

最佳答案

在使用迭代器的部分中,使用以下内容:

// deal cards
for (Player p : players) {
p.drawCard(gameDeck.dealNextCard());
}

这个for (Player p : players)称为增强for 循环,有时也称为for-each 循环。它循环遍历 Iterable 中的每个项目。目的。安Iterable object 是一个实现 Iterable 的对象界面。

players ,其类型为 ArrayList<Player> ,实现Iterable<Player>接口(interface),因此可以在增强的 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

希望这有帮助!

关于java - 向玩家数组列表发一张牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25026935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com