索引超出范围的异常数组

时间:2014-03-29 03:32:39

标签: c# windows indexoutofrangeexception

我不明白为什么我会超出范围错误。是否我的代码设置不正确,以便在输入每个单词时增加数组的大小?注意:我这里没有显示一些类。请告诉我,为了在每次输入新单词时使数组增加1,我必须做什么。

 class Program
{
    static String[] Parse(String commandLine)
    {
        string[] stringSeparators = new string[] { "" };
        String[] localList = new String[commandLine.Count((char f) => f == ' ') + 1];
        localList = commandLine.Split(stringSeparators, StringSplitOptions.None);
        return localList;
    }
    static void Main(string[] args)
    {
        Verb cVerb = new Verb(); //constructors begin here
        Noun cNoun = new Noun();
        Item itemName = new Item();
        Player myPlayer = new Player();
        String commandLine;

        Room northRoom = new Room();
        Room southRoom = new Room();

        northRoom.setRoomDesccription("You stand in the center of the northern room. It smells musty");
        southRoom.setRoomDesccription("You stand in the center of the southern room. It is made of crumbling stone");

        myPlayer.setRoom(northRoom);

        Console.WriteLine("Welcome young hero, to the world of Argandia");           
        while (cVerb.getName() != "Exit") // continue playing as long as verb entered =/ "exit"
        {
            //Room Description
            myPlayer.getRoom().printDesc();

            //Player Input
            Console.WriteLine("You can now type a verb then a noun");
            commandLine = Console.ReadLine();
            int numWords = commandLine.Count((char f) => f == ' ') + 1;
            String[] verbNounList = new String[numWords];
            verbNounList = Parse(commandLine);



            //process input
            if (numWords > 0)
            {
                cVerb.setName(verbNounList[0]);
                if (cVerb.getName() == "Exit")
                {
                    Console.WriteLine("Thanks for playing\nSee you next time\nPress any key to exit...");
                    Console.ReadKey();
                    Environment.Exit(0);
                }
                if (numWords > 1)
                {
                    cNoun.setName(verbNounList[1]);
                }
                if (numWords == 2)
                {

                }
                else
                {
                    Console.WriteLine("We are only able to support 2 words at this time, sorry\nPress any key to continue...");
                }

            }



        }
    }
}

1 个答案:

答案 0 :(得分:0)

也许您应该使用像List<string>这样的集合。数组的动态替代:

 public static IEnumerable<string> Parse(string commandLine)
    {
        foreach (var word in commandLine.Split(' '))
            yield return word;
    }

    static void Main(string[] args)
    {
        string testCommandLine = "Hello World";
        var passedArgs = Parse(testCommandLine);
        foreach (var word in passedArgs)
        { 
            //do some work
            Console.WriteLine(word);
        }

        Console.Read();
    }