在C#数组运行时的异常处理#

问题描述:

我是编程初学者,我在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)可能在此处引发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

我在这个程序中发布了有关此方法的其他问题的2个解决方案,它以两种不同的方式解决了阵列大小问题。使用int.TryParse而不是convert,你需要根据用户对学生数量的输入来调整数组的大小,或者你需要检查答案数组每次迭代中的空值,忽略空值。请参阅我在其他问题中提供的示例代码。