[英]C# User Input Loop Skipping Code
编码非常新。 我发布了一个有关如何在不使程序崩溃的情况下检查无效用户输入的问题,该问题很快得到了解答,谢谢! 现在,我已将循环设置为拒绝除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之间的强度值:
输入的强度值无效。
请输入介于1到10之间的速度值:5
强度值= 0
速度值= 5
如何获得此代码,以不断询问强度值,直到给出有效数字,然后继续提高速度? 谢谢!
将您的代码更改为:
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.