2016-01-24 43 views
0

我是編程初學者,我在C#中嘗試過一些簡單的代碼。 [1]:http://i.stack.imgur.com/zLVbz.jpg 該代碼處理簡單的數組初始化,存儲和排序等。它在第一次嘗試中照常運行,但是當我再次想要存儲在數組中時,它會拋出我不理解的異常。 [![其異常我越來越] [1] [1]在C#數組運行時的異常處理#

static void Main(string[] args) 
     { 
     int number; 
     char y; 

     string[] answer = new string[10]; 
     bool keeprompting = true; 
     while (keeprompting) 

     { 
      Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n"); 
      int input = Convert.ToInt16(Console.ReadLine()); 

      switch (input) 
      { 

       case 1: 
        Console.WriteLine("Enter the Number of Students to be added to the List"); 
        number = Convert.ToInt16(Console.ReadLine()); **exception** 

        for (int i = 0; i < number; i++) 
        { 
         answer[i] = Console.ReadLine(); 
        } 

        break; 




       case 2: 

        foreach (var item in answer) 
        { 
         Console.WriteLine(item.ToString()); 
        } 
        break; 
       case 3: 

        Array.Sort(answer); 
        foreach (var item in answer) 
        { 
         Console.WriteLine(item.ToString()); **exception** 
        } 
        break; 



       case 4: 
        Console.WriteLine("Are you sure you want to exit"); 
        Console.WriteLine("1 for Yes and for No"); 
        y = (char)Console.Read(); 
        if (y != 1) 
        { 
         keeprompting = true; 
        } 
        else 
        { 
         keeprompting = false; 
        } 
        Console.WriteLine("thank you"); 

        break; 


      } 

     } 


    } 
} 

} 任何及所有建議都歡迎。

+0

輸入字符串格式不正確意味着輸入的文本不是整數。最好使用'Int16.TryParse'。 – Tim

回答

1

1)可能在此處引發FormatException int input = Convert.ToInt16(Console.ReadLine());,因爲您進入控制檯時不是'1','2'等,而是'1.','2'。等等。或者,您可能使用了其他不能使用Convert.ToInt16()方法解析的符號。輸入的值應該在-32768..32767的範圍內,並且不得包含除減號外的任何空格,點,逗號和其他符號。

2)同樣可能發生在這裏number = Convert.ToInt16(Console.ReadLine()); **exception**

3)在這裏,我想你的NullReferenceException:

Array.Sort(answer); 
foreach (var item in answer) 
{ 
    Console.WriteLine(item.ToString()); **exception** 
} 

這是因爲您在陣列(string[] answer = new string[10];)中有10個項目,但是當你插入學生你可以插入少於10個,所以你有3個項目初始化,其他設置爲默認值 - nullstring。所以你的數組看起來像這樣:{ "John", "Jack", "Ben", null, null, ..., null }。後面的語句會迭代每個包含空值的項目,並嘗試調用空對象的方法,因此您會得到NullReferenceException。
也許你應該更好地使用List<string>而不是數組來避免這類問題。在再次進入學生之前撥打Add()添加項目,並撥打Clear()方法(從以前的「課程」中免費學習)。當你以後用foreach循環迭代這個集合時,一切都會好起來的。

+0

它就像基本的任務,所以我想用數組 – vikram

1

我在這個程序中發佈了有關此方法的其他問題的2個解決方案,它以兩種不同的方式解決了陣列大小問題。使用int.TryParse而不是convert,你需要根據用戶對學生數量的輸入來調整數組的大小,或者你需要檢查答案數組每次迭代中的空值,忽略空值。請參閱我在其他問題中提供的示例代碼。