编码很新。我发布了一个关于如何在不崩溃程序的情况下检查无效用户输入的问题,这很快就回答了,谢谢!我现在已经设置了循环设置以拒绝任何除了1-10之间的值之外的任何东西并尝试让它进入下一个要输入的属性但是无法弄清楚如何阻止它跳转到代码结束。这是我的代码:
UInt32 attributePoints = 25;
bool validInput = false;
string inputStrength;
string inputSpeed;
UInt32 validStrength = 0;
UInt32 validSpeed = 0;
while (!validInput)
{
Console.WriteLine("You have: " + attributePoints + " attribute points remaining to choose from");
Console.Write("Please enter a value between 1-10 for strength: ");
inputStrength = Console.ReadLine();
if (!UInt32.TryParse(inputStrength, out validStrength))
{
Console.WriteLine("Input was not a valid value for strength.");
}
else if (validStrength < 0 || validStrength > 10)
{
Console.WriteLine("Input was not a valid value for strength.");
}
else
{
validInput = true;
}
while (!validInput)
{
Console.Write("Please enter a value between 1-10 for speed: ");
inputSpeed = Console.ReadLine();
if (!UInt32.TryParse(inputSpeed, out validSpeed))
{
Console.WriteLine("Input was not a valid value for speed.");
}
else if (validSpeed < 0 || validSpeed > 10)
{
Console.WriteLine("Input was not a valid value for speed.");
}
else
{
validInput = true;
}
}
Console.WriteLine(String.Format("Strength Value = {0}", validStrength));
Console.WriteLine(String.Format("Speed Value = {0}", validSpeed));
}
如果我运行程序故意输入无效的速度输入,最终结果如下:
请输入1-10之间的强度值:a
输入不是力量的有效值。
请输入1-10之间的速度值:5
强度值= 0
速度值= 5
如何在获得有效数字然后继续加速之前,如何让这段代码继续询问强度值?谢谢!
答案 0 :(得分:0)
将您的代码更改为:
UInt32 attributePoints = 25;
string inputStrength;
string inputSpeed;
UInt32 validStrength = 0;
UInt32 validSpeed = 0;
while (true)
{
Console.WriteLine("You have: " + attributePoints + " attribute points remaining to choose from");
Console.Write("Please enter a value between 1-10 for strength: ");
inputStrength = Console.ReadLine();
if (!UInt32.TryParse(inputStrength, out validStrength))
Console.WriteLine("Input was not a valid value for strength.");
else if (validStrength < 0 || validStrength > 10)
Console.WriteLine("Input was not a valid value for strength.");
else
break;
}
while (true)
{
Console.Write("Please enter a value between 1-10 for speed: ");
inputSpeed = Console.ReadLine();
if (!UInt32.TryParse(inputSpeed, out validSpeed))
Console.WriteLine("Input was not a valid value for speed.");
else if (validSpeed < 0 || validSpeed > 10)
Console.WriteLine("Input was not a valid value for speed.");
else
break;
}
Console.WriteLine(String.Format("Strength Value = {0}", validStrength));
Console.WriteLine(String.Format("Speed Value = {0}", validSpeed));