Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();
int newUserInput = Convert.ToInt32(userInput);
if (!int.TryParse(userInput, out newUserInput))
{
Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}
有人可以向我解释为什么我的错误消息没有显示,以及为什么int newUserInput
行收到的错误信息没有正确格式化?
答案 0 :(得分:2)
试试这个:
Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();
int newUserInput;
if (!int.TryParse(userInput, out newUserInput))
{
Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}
只需在此int.TryParse(userInput, out newUserInput)
开展工作,而不是在TryParse
答案 1 :(得分:0)
这完全取决于您使用
发送的内容Console.ReadLine()
另外,请参阅以下内容:
如果Convert.ToInt32
输入不正确, FormatException
会抛出Int32
。请参阅Convert.Int32(MSDN)
此外,您似乎再次使用Convert.Int32
覆盖TryParse
。你实际上不需要Convert.Int32
Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();
int newUserInput; //dont assign anything
if (!int.TryParse(userInput, out newUserInput))
{
Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}