我是編程初學者,我在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;
}
}
}
}
} 任何及所有建議都歡迎。
輸入字符串格式不正確意味着輸入的文本不是整數。最好使用'Int16.TryParse'。 – Tim