2014-03-29 104 views
0

我不明白为什么我得到超出范围的错误。我的代码是否设置不正确,导致输入的每个单词的大小都增加?注意:我有一些类未在此处显示。请告诉我为了在每次输入一个新单词时增加一个数组,我必须做的事情。索引超出范围异常数组

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..."); 
       } 

      } 



     } 
    } 
} 

回答

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(); 
    }