错误消息未显示;转换不正确

时间:2018-03-11 08:29:11

标签: c#

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行收到的错误信息没有正确格式化?

2 个答案:

答案 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: ");


    }