1

下面附上代码。我正在编写一个菜单,用户输入一个数字来选择一个菜单选项。它也包含在一个while循环中,因此用户可以一遍又一遍地重复菜单。它在第一个循环中完美运行,但在第二个循环中它给出“输入字符串格式不正确”。在 Console.ReadLine()

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();
    }
4

2 回答 2

1

int.TryParseint.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";
于 2015-05-30T18:08:41.160 回答
1
    int option = int.Parse(Console.ReadLine());

专注于编写可调试的代码:

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

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

通过使用 Console.ReadKey() 来获得成功。并使用 int.TryParse() 这样一个简单的输入错误就不会导致您的程序崩溃。

于 2015-05-30T18:29:32.633 回答