0

範囲外エラーが発生する理由がわかりません。単語が入力されるたびに配列のサイズが大きくなるようにコードが正しく設定されていませんか? 注: ここに表示されていないクラスがいくつかあります。新しい単語が入力されるたびに配列を 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...");
                }

            }



        }
    }
}
4

1 に答える 1

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();
    }
于 2014-03-29T03:54:19.393 に答える