【发布时间】:2016-09-07 11:28:48
【问题描述】:
我对下面的代码有一些问题。我还在学习,不知道如何解决。
1 .-我要做的是创建一个方法 (GetInt) 来存储变量,就像我在第二个方法 (GetTrack) 中尝试做的那样,它将进入我的主要方法。
2.-当输入无效时,我无法让 GetInt 方法循环,我猜 try/catch 和布尔值有问题
谢谢
//Get int Method
static public void GetInt(string sPrompt, int iMin, int iMax)
{
int iNum;
bool bError = false;
do
{
bError = true;
try
{
Console.Write(sPrompt);
iNum = int.Parse(Console.ReadLine());
if ((iNum < iMin) || (iNum > iMax))
{
Console.WriteLine("The value is out of range.");
bError = true;
}
}
catch (ArgumentException)
{
Console.WriteLine("An invalid number was entered, please try again.");
bError = true;
}
}
while (bError == false);
}
//Get Track Method
static public void GetTrack()
{
int iMin;
int iSec;
iMin = GetInt("Enter the minutes: ", 0, 10);
iSec = GetInt("Enter the seconds: ", 0, 59);
}
【问题讨论】:
-
在
void上进行快速 Google 搜索,以及 void 方法的作用......关于return values -
你的
try只包装iNum = int.Parse(Console.ReadLine());可能会稍微好一点,这样你就不会捕捉(并忽略)其他异常。例如,如果sPrompt是null,那么Console.Write将抛出异常,但您的程序将简单地捕获该异常并说“无效的数字,再试一次”,即使数字是有效的,它是sPrompt是无效的.
标签: c# methods boolean try-catch do-while