代码告诉我输入何时不是数字,但是如果代码同时也写入else
我相信这与我在顶部双变量中将数字0分配给doubleNr有关,但如果我没有,我得到 使用未分配的局部变量'doubleNr' 在有条件的情况下坚强>
另外,我在哪里写下 doubleNr = myMethod(intNr); 行?
在try块中还是在catch和if块之间?
int intNr;
double doubleNr = 0;
while (doubleNr < 20 || doubleNr > 30)
{
Console.WriteLine("Enter your number: ");
string strNr = Console.ReadLine();
try
{
intNr = Convert.ToInt32(strNr);
doubleNr = myMethod(intNr); // Should this line go here?
}
catch
{
Console.WriteLine("Number must be INT");
}
// or should it go here?
if (doubleNr < 20)
{
Console.WriteLine("Try a higher number.");
}
else if (doubleNr > 30)
{
Console.WriteLine("Try a lower number.");
}
}
Console.WriteLine("That is a good number.");
答案 0 :(得分:2)
这可能不值得回答,但我只是想在你的代码中指出一些事情。由于您需要使用try-catch
,因此您可以简单地实现retry-catch
。要做到这一点,你应该使用while(true)
和try-catch逻辑来控制程序的流程,如@Pikoh所说。
public static void Main(string[] args)
{
int intNr;
double doubleNr = 0;
while(true)
{
try
{
Console.WriteLine("Enter your number: ");
string strNr = Console.ReadLine();
doubleNr = Int32.Parse(strNr);
if(doubleNr < 20)
{
throw new Exception("Try a higher number.");
}
else if(doubleNr > 30)
{
throw new Exception("Try a lower number.");
}
else
{
Console.WriteLine("That is a good number.");
break;
}
}
catch(FormatException e)
{
Console.WriteLine("Enter a valid number.");
continue;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
continue;
}
}
}
在这里,您可以看到while
循环不会调节您的程序,try-catch
逻辑将控制它。当然还有其他方法可以做到这一点,但这只是对代码的重组。
正如您所知,还有更好的方法可以做到这一点。您可以使用Int32.TryParse()
,在这种情况下最好。无需使用任何try-catch
块。
public static void Main(string[] args)
{
int intNr;
double doubleNr = 0;
while(true)
{
Console.WriteLine("Enter your number: ");
string strNr = Console.ReadLine();
int value;
if(Int32.TryParse(strNr, out value))
{
doubleNr = value;
}
else
{
Console.WriteLine("Enter a valid number: ");
continue;
}
if(doubleNr < 20)
{
Console.WriteLine("Try a higher number.");
continue;
}
else if(doubleNr > 30)
{
Console.WriteLine("Try a lower number.");
continue;
}
else
{
Console.WriteLine("That is a good number.");
break;
}
}
}
答案 1 :(得分:-1)
如果要在异常或任何其他条件下跳过当前循环步骤,请使用continue语句。
continue语句将控制传递给下一次迭代 附上,发表,发表或发表声明的声明。
这是带有continue
语句的代码示例。
int intNr;
double doubleNr = 0;
while (doubleNr < 20 || doubleNr > 30)
{
Console.WriteLine("Enter your number: ");
string strNr = Console.ReadLine();
try
{
intNr = Convert.ToInt32(strNr);
// if you want to catch any exceptions in this method then leave it there
// otherwise you can move it outside try/catch block
doubleNr = myMethod(intNr);
}
catch
{
Console.WriteLine("Number must be INT");
continue; // return to the beginning of your loop
}
if (doubleNr < 20)
{
Console.WriteLine("Try a higher number.");
continue; // return to the beginning of your loop
}
// do not need else since code wont reach this line if doubleNr is < 20
if (doubleNr > 30)
{
Console.WriteLine("Try a lower number.");
continue; // return to the beginning of your loop
}
}
Console.WriteLine("That is a good number.");