C# List.RemoveAt在第二次迭代时引发异常

C# List.RemoveAt在第二次迭代时引发异常,c#,list,C#,List,我正在将一些旧的作业从Java移植到C#,我不断得到ArgumentOutOfRange异常,试图从列表中删除元素。我在一个对象上调用一个方法,该对象反过来在包含列表的类上调用一个静态方法 我在一组玩家对象上循环,将卡片从DeckOfCards复制到玩家手中,然后从DeckOfCards中移除该卡片。它在第一次迭代中工作,在第二次迭代中失败 编辑:根据要求,以下是相关文件的完整代码 Runner.cs using System; public class Runner { publi

我正在将一些旧的作业从Java移植到C#,我不断得到ArgumentOutOfRange异常,试图从列表中删除元素。我在一个对象上调用一个方法,该对象反过来在包含列表的类上调用一个静态方法

我在一组玩家对象上循环,将卡片从DeckOfCards复制到玩家手中,然后从DeckOfCards中移除该卡片。它在第一次迭代中工作,在第二次迭代中失败

编辑:根据要求,以下是相关文件的完整代码

Runner.cs

using System;

public class Runner
{

    public static void Main(String[] args){


       int choice = -1;

        while(choice != 3){
            Console.WriteLine("\nBlackjack!");
            Console.WriteLine("Press 1 to choose the timid strategy.");
            Console.WriteLine("Press 2 to choose the aggressive strategy.");
            Console.WriteLine("Press 3 to exit.");

            string input = Console.ReadLine();

            try
            {
                choice = Convert.ToInt32(input);
                if ((choice == 1) || (choice == 2))
                {
                    BlackJack game = new BlackJack(choice);
                    game.playRound();
                    /*Console.WriteLine(DeckOfCards.cardCount());
                    DeckOfCards.draw();
                    Console.WriteLine(DeckOfCards.cardCount());
                    DeckOfCards.draw();
                    Console.WriteLine(DeckOfCards.cardCount());
                    Console.WriteLine(DeckOfCards.topCard());*/
                }

                else if (choice == 3)
                {
                    Console.WriteLine("\nThanks for playing!");
                }

                else
                {
                    Console.WriteLine("\nPlease enter a number between 1 and 3");
                }
            }
            catch (OverflowException)
            {
                Console.WriteLine("\nPlease enter a number between 1 and 3");
            }
            catch (FormatException)
            {
                Console.WriteLine("\nPlease enter a number between 1 and 3");
            }

        }
    }
}
21点

using System;
using System.Collections;

public class BlackJack {

    private Player[] players;

    /*
     * Passes an integer value to player to determine which strategy the Player object will have.
     * Sets up the DeckOfCards and adds both Player objects to an array.
     * @require integer value 1 or 2
     * @ensure this.players[0] will have a non-null strategy object and both players added to an array 
    */   
    public BlackJack(int choice) {
        DeckOfCards.resetDeck();
        this.players = new Player[2];
        this.players[0] = new Player(choice, "Player"); //player
        this.players[1] = new Player("Dealer"); //dealer
    }

    /*
     * Plays the game, with each player hitting until the hand value specifed by his strategy is reached
     * or his hand value is greater than 21.
     * @require two non-null player objects
     * @ensure Players hit according to the specified strategies or until hand > 21
    */
    public void playRound() {
        for (int i = 0; i < this.players.Length; i++) { 
            this.players[i].takeTurn();
            this.players[i].showHand();
            //Console.WriteLine(DeckOfCards.cardCount());
            //DeckOfCards.showDeck();
        }

        //If the player's hand is greater than the dealer's hand and less than or equal to 21
        if(this.players[0].handValue() > this.players[1].handValue() && this.players[0].handValue() <= 21){
            Console.Write("Player wins!");
        }
        //If the player's hand is less than or equal to 21 and the dealer has busted
        else if((this.players[0].handValue() <= 21) && this.players[1].handValue() > 21){
             Console.Write("Player wins!");    
        }
        //Otherwise, the dealer has won.
        else{
             Console.Write("Better luck next time, pal.");
        }

    }

}

我做错了什么?这在Java中很简单。

hitOrStand方法总是返回1:

public int hitOrStand(int handValue) {
    int result = 1;

    if(handValue >= 17){
        result = 1;
    }
    else if(handValue < 1){
        result = 1;
    }

    return result;
}

我怀疑另一种策略正用于
hitOrStand
,该策略也返回了不正确的值,否则,正如发布的那样,这将导致无限循环。

可能牌组只有一个项目。如何填充牌组对象?这是我的第一个想法,但列表不会自动重新索引?甲板[1]不是变成甲板[0]了吗?我们真的需要看到一个最小但完整的程序来演示这个问题。我们所看到的代码中仍然没有任何错误。@LarsTech你是绝对正确的,我觉得自己很笨。我的策略出了错,牌快用完了。在DealerStrategy.cs中,我有一个1,其中0应该是。其他两种策略都没有犯这个错误。我现在该怎么处理这个问题?就是这样。它总是在轮到经销商时崩溃,因为经销商策略是唯一一个从未返回0的策略。
using System;

public class Player {

    private Hand hand;
    private string name;
    private IStrategy myStrategy;

    /*
     * Constructor, sets up the Player object
     * @require integer value 1, 2, or 3, string name
     * @ensure Player with empty hand, specified name and selected strategy
    */
    public Player(int choice, string name){
        this.hand = new Hand();
        this.name = name;

        if(choice == 1){
            this.myStrategy = new TimidStrategy();
        }
        else if(choice == 2){
            this.myStrategy = new AggressiveStrategy();
        }
        else{
            this.myStrategy = new DealerStrategy();
        }
    }

    /*
     * Overloaded, sets up the Player object
     * @require string name
     * @ensure Player with specified name and dealer strategy
    */
    public Player(string name)
    {
        this.hand = new Hand();
        this.name = name;
        this.myStrategy = new DealerStrategy();
    }

    /*
     * Adds a card to the player's hand
     * @require deck > 0 cards
     * @ensure hand + 1 card, deck - 1 card
    */
    public void giveCard()
    {
        hand.addCard(DeckOfCards.draw());
    }

    /*
     * Adds card to the hand until the hand value reaches the limit specified in the stratgy or exceeds 21.
     * Checks for aces in a hand that exceeds 21 and changes them from 11 to 1 point if present.
     * @require non-null hand, deck >= 0 cards
     * @ensure cards added to hand until strategy limit is reached or 21 is exceeded
    */
    public void takeTurn()
    {
        int hitMe = 1;
        while (hitMe == 1)
        {
            giveCard();

            if (hand.getValue() > 21)
            {
                hand.changeAceValue();
            }

            hitMe = this.myStrategy.hitOrStand(hand.getValue());
        }
        /*
         * Note to self: This originally malfunctioned because the hitMe/myStrategy assignment needed to be last, not first.
         * The pieces of this method are all tested separately.
        */
    }

    /*
     * Prints the results of the round
     * @require non-null hand >= 0 cards
     * @ensure hand point value printed to screen
    */
    public void showHand(){
        Console.WriteLine();
        hand.showHand();
        if(hand.getValue() <= 21){
            Console.WriteLine(this.name + " stands at " + hand.getValue());
        }
        else if(hand.getValue() > 21){
           Console.WriteLine("Bust! " + this.name + " is over by: " + (hand.getValue() - 21));
        }
    }

    /*
        * Returns the player's name
        * @require string name != null
        * @ensure returns the player's name
       */
    public string getName()
    {
        return this.name;
    }


    //Methods from here till EOF for testing purposes only

    /*
     * Returns the hand's value.
     */
    internal int handValue()
    {
        return hand.getValue();
    }

    /*
     * Deals a card worth one point.
     * Used to test whether a player will stand at the value specified in his strategy.
     */
    internal void standTest()
    {
        int hitMe = 1;
        while (hitMe == 1)
        {
            hand.addCard(new Card("Worth One", 1));
            hitMe = this.myStrategy.hitOrStand(hand.getValue());
        }
    }

    internal int cardCount()
    {
        return this.hand.cardCount();
    }

}
using System;
public class DealerStrategy : IStrategy{
    /*
     * Determines whether the player will hit or stand based on the value of his hand.
     * @require integer value >= 0
     * @ensure positive integer result
    */
    public int hitOrStand(int handValue) {
        int result = 1;

        if(handValue >= 17){
            result = 1;
        }
        else if(handValue < 1){
            result = 1;
        }

        return result;
    }
}
System.ArgumentOutOfRangeException was unhandled
  HResult=-2146233086
  Message=Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
  Source=mscorlib
  ParamName=index
  StackTrace:
       at System.ThrowHelper.ThrowArgumentOutOfRangeException()
       at System.Collections.Generic.List`1.get_Item(Int32 index)
       at DeckOfCards.draw()
       at Player.giveCard()
       at Player.takeTurn()
       at BlackJack.playRound()
       at Runner.Main(String[] args)
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
public int hitOrStand(int handValue) {
    int result = 1;

    if(handValue >= 17){
        result = 1;
    }
    else if(handValue < 1){
        result = 1;
    }

    return result;
}
public void takeTurn()
{
    int hitMe = 1;
    while (hitMe == 1)
    {
        giveCard();

        if (hand.getValue() > 21)
        {
            hand.changeAceValue();
        }

        hitMe = this.myStrategy.hitOrStand(hand.getValue());
    }
    /*
     * Note to self: This originally malfunctioned because the hitMe/myStrategy assignment needed to be last, not first.
     * The pieces of this method are all tested separately.
    */
}