当我尝试输入退出字符串xxx时,为什么会抛出异常?它工作在而循环,但不与做...而循环。C# - 循环将不接受Convert.ToInt32(...)后的非数字输入
当我转换为整数后,字符串变量只允许使用数字字符(如-999)退出做...而循环。但我想让循环控制变量变成“退出”而不是数字。我怎样才能做到这一点?
这是我的代码。
using System;
namespace StringInputPractice
{
class StringInputPractice
{
static void Main()
{
// Declarations
string inValue;
int first;
int second;
int sum;
do
{
Console.Write("\nEnter the first number. (Type \"xxx\" to exit): ");
inValue = Console.ReadLine();
first = Convert.ToInt32(inValue); //@@@@@
Console.Write("\nEnter the second number. (Type \"xxx\" to exit): ");
inValue = Console.ReadLine();
second = int.Parse(inValue);
sum = first + second;
Console.WriteLine("\nThe sum of {0} and {1} is {2}.", first,
second, sum);
/* Things I've tried inside do { } and that don't work */
//inValue = "";
//inValue = null;
//inValue = inValue.ToString();
//inValue = first.ToString();
//inValue = second.ToString();
}
while (inValue != "xxx"); /*If you enter a non-numeric string,
* an exception is thrown at
* @@@@@ above.
*/
Console.ReadLine();
}
}
}
哦,下一次你遇到一些抛出异常的代码时,请告诉哪种异常:),这将有助于整个死亡! :b – f2lollpll 2012-02-28 05:19:11