在循环的第二步获得 "Input string was not in a correct format."

Getting "Input string was not in a correct format." on SECOND step thru loop

下面附上代码。 我正在编写一个菜单,用户可以在其中输入一个数字 select 一个菜单选项。它还包含在一个 while 循环中,因此用户可以一遍又一遍地重复菜单。 它在第一个循环中完美运行,但在第二个循环中它在 Console.ReadLine()

处给出 "Input string was not in a correct format."
static void Main(string[] args)
    {
        bool again = true;
        while (again)
        {

            string yourName = "Someone";

            Console.WriteLine("\t1: Basic Hello, World.\n" +
                "\t2: Calculate demoninations for a given value of change.\n" +
                "\t3: Calculate properties of shapes.\n" +
                "Please Select an Option: ");
            int option = int.Parse(Console.ReadLine());//errors out here.
            switch (option)
            {

            }
            Console.Write("Press y to back to the main menu.  Press any other key to quit: ");
            char againChoice = (char)Console.Read();
            if (againChoice == 'y')
            { again = true; }
            else
            { again = false; }
        }
        Console.Write("Hit Enter to end");
        Console.Read();
    }
当您不确定用户输入的输入值

时,

int.TryParse 是比 int.Parse 更好的方法

int option;
if(int.TryParse(Console.ReadLine(), out option))
{
  switch (option)
  {

  }
}
Console.Write("Press y to back to the main menu.  Press any other key to quit: ");
char againChoice = (char)Console.Read();
// also add read line to capture enter key press after press any key
Console.ReadLine();

或将返回菜单代码更改为

string againChoice = Console.ReadLine();
again =againChoice == "y";
    int option = int.Parse(Console.ReadLine());

专注于编写可调试代码:

    string input = Console.ReadLine();
    int option = int.Parse(input);

现在您可以使用调试器,在 Parse() 语句上设置断点。您会很容易地明白为什么 Parse() 方法抛出异常。是的,它不喜欢空字符串。现在您可以找到代码中的错误,Console.Read() 需要您按 Enter 键才能完成,但只有 returns 一个字符。 Enter 键仍未处理,您将在下一次读取调用时获得它。轰隆隆。

使用 Console.ReadKey() 代替。并使用 int.TryParse() 这样一个简单的输入错误就不会使您的程序崩溃。