日期:2014-05-19  浏览次数:20757 次

重发请问:为什么会这样呢?谢谢~
do
{
        Console.WriteLine( "Select   a   direction(between   1   and   4): ");
        myDirection   =   Convert.ToInt32(Console.ReadLine());
        //string-> int32,为什么输入a出错,而按f6仅仅是重新输入呢?
  }
        while   ((myDirection   <   1)   ||   (myDirection   >   4));

不太明白,请指点,谢谢!


------解决方案--------------------
myDirection = Convert.ToInt32(Console.ReadLine().Trim());
该句负责读取用户输入数据,这里只能输入数字。如果输入字符例如:a,在Convert.ToInt32会产生异常,他只负责将字符串解析为数值,即“65” --> 65

------解决方案--------------------
看这页Exception部分为什么会出错
http://msdn2.microsoft.com/en-us/library/sf1aw27b(VS.90).aspx
执行ToInt32( "a ")会抛出异常
Console.ReadLine())对于F6得到null
而ToInt32(null)返回0