我无法弄清楚我做错了什么。我想要做的是获取用户输入并验证它是一个介于 1 到 4 之间的数字,并且没有其他任何事情会导致程序崩溃。但我无法让 tryparse 号码验证工作。它不会在里面运行代码。1 和 5 之外的任何整数都不会引发错误,但输入小数、字符串等会引发错误。它是一个明显的修复,但我似乎无法弄清楚。
class Program
{
static void Main(string[] args)
{
string[] ColorsArray = new string[12] { "blue", "red", "green", "yellow", "blue", "green", "blue", "yellow", "red", "green", "red", "yellow" };
float[] LengthArray = new float[12] { 1.3f, 1.4f, 5.6f, 1.5f, 3.5f, 5.4f, 1.2f, 6.5f, 4.4f, 4.1f, 3.3f, 4.9f };
Console.WriteLine("Select a color of Fish by entering the corresponding number \r\n 1. Blue \r\n 2. Yellow \r\n 3. Red \r\n 4. Green");
string ColorChoiceNumber = Console.ReadLine();
int ColorChoiceNumberInt = int.Parse(ColorChoiceNumber);
if (ColorChoiceNumberInt == 1)
{
Console.WriteLine("The Biggest Blue Fish is Fish Number ");
}
else if (ColorChoiceNumberInt == 2)
{
Console.WriteLine("The Biggest Yellow Fish is Fish Number");
}
else if (ColorChoiceNumberInt == 3)
{
Console.WriteLine("The Biggest Red Fish is Fish Number");
}
else if (ColorChoiceNumberInt == 4)
{
Console.WriteLine("The Biggest Green Fish is Fish Number");
}
else if (!(int.TryParse(ColorChoiceNumber, out ColorChoiceNumberInt)) && ColorChoiceNumberInt < 1 && ColorChoiceNumberInt > 4)
{
Console.WriteLine("Please only enter a number. It must be 1-4.");
ColorChoiceNumber = Console.ReadLine();
int.TryParse(ColorChoiceNumber, out ColorChoiceNumberInt);
}
else
{
Console.WriteLine("Please only enter a number. It must be 1-4.");
ColorChoiceNumber = Console.ReadLine();
int.TryParse(ColorChoiceNumber, out ColorChoiceNumberInt);
}
}
}
}
一般来说,要从用户那里获得有效的输入,你只需要做几件事:
int
调用前声明变量int.TryParse
out
参数传递给int.TryParse
int.TryParse
变量的返回值和边界检查作为循环的一部分,因此用户被迫输入指定范围内的有效数字例如,以下代码首先显示选项,然后不断询问用户是否输入有效信息,直到他们输入为止:
// Present the options
Console.WriteLine(" 1. Blue \r\n 2. Yellow \r\n 3. Red \r\n 4. Green");
// This variable will hold their input after the TryParse call
int ColorChoiceNumberInt;
// Continue to ask for input until they enter an integer between 1 and 4
do
{
Console.Write("Select a color of Fish by entering the corresponding number (1-4): ");
} while (!int.TryParse(Console.ReadLine(), out ColorChoiceNumberInt) ||
ColorChoiceNumberInt < 1 ||
ColorChoiceNumberInt > 4);
我过去所做的是为此创建一个辅助函数,因此可以在整个程序中轻松重复使用该逻辑:
public static int GetIntFromUser(string prompt, int minValue = int.MinValue,
int maxValue = int.MaxValue)
{
int input;
do
{
Console.Write(prompt);
} while (!int.TryParse(Console.ReadLine(), out input) ||
input < minValue ||
input > maxValue);
return input;
}
使用这个辅助方法,您的主要代码突然变得更加简单:
Console.WriteLine(" 1. Blue \r\n 2. Yellow \r\n 3. Red \r\n 4. Green");
int input = GetIntFromUser("Select a fish color (1-4): ", 1, 4);
Console.WriteLine("You entered: " + input);
输出
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句