當我嘗試輸入退出字符串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