【发布时间】:2018-12-31 16:25:52
【问题描述】:
我在尝试打印数组中的最后一个元素时遇到异常。
这是我的代码:
int[] nums = { 1, 2, 5, 7, 8 };
Console.WriteLine("first element is " + nums[0]);
int fe = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Last element is {0}" , nums[nums.Length - 1]);
int le = Convert.ToInt32(Console.ReadLine());
例外:
第一个元素是 1
未处理的异常:System.FormatException:输入字符串的格式不正确。 在 System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) 在 System.Number.ParseInt32(String s,NumberStyles 样式,NumberFormatInfo 信息) 在 System.Convert.ToInt32(字符串值) 在 C:\Users\SudhaPraveen\Documents\Visual Studio 2017\Projects\CSharpPractice21DaysPlan\W2Resource\BasicExProb51.cs:line 16 中的 W2Resource.BasicExProb51.Main() 按任意键继续 。 . .
【问题讨论】:
-
调试看看
Console.ReadLine()返回了什么。 -
提示:当你认为异常并没有发生。
-
您对 Console.ReadLine 的输入是什么?
-
查看你的堆栈跟踪,你会找到导致异常的方法,它以
at...开头。与您使用的方法进行比较,然后您就知道Convert.ToInt32引发了该异常。为什么?因为控制台中的内容不是有效的整数 -
Console.ReadLine() 不是整数,这就是它抛出异常的原因
标签: c#