索引超出范围异常数组

本文关键字:异常 数组 范围 索引 | 更新日期: 2023-09-27 17:54:36

我不明白为什么我得到一个超出范围的错误。我的代码是否设置不当,使数组的大小随着每个单词的输入而增加?注意:我有一些类没有显示在这里。请告诉我该怎么做才能使数组在每次输入一个新单词时增加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...");
                }
            }

        }
    }
}

索引超出范围异常数组

也许您应该使用像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();
    }