【发布时间】:2022-01-25 02:48:01
【问题描述】:
我在运行下面的代码时遇到错误“使用未分配的变量'尝试'”,我不明白原因,因为据我了解,try 语句块总是运行,所以变量应该由用户?还是我错了?如果有人有我修复或解决它会有所帮助。
static void MagicNumber(int rndMin, int rndMax, int lives = 4)
{
Random rnd = new Random();
int rndNum = rnd.Next(rndMin, rndMax);
int attempt;
do
{
try
{
Console.WriteLine($"Remaining lives : {lives}");
Console.WriteLine($"Enter a number between {rndMin} and {rndMax} :");
attempt = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Error : Enter a number !");
}
} while ((lives > 0) || (attempt < rndMin) || (attempt > rndMax));
}
MagicNumber(1, 40, 5);
【问题讨论】:
-
如果
Console.WriteLine抛出异常会怎样? -
可能是
Console.Readline在尝试变量分配之前抛出异常。 -
@Eduardomacedo 这是编译时错误,而不是运行时错误。它是为
while子句中的attempt变量抛出的。 -
@gunr2171 哦!是的,你是对的。
标签: c#