繁体   English   中英

输入字符串的格式不正确。 不确定如何转换输入字符串 c#

[英]Input string was not in a correct format. Not sure how to convert input string c#

我有一个井字游戏解决方案。 我的代码运行到两个用户都可以输入他们的名字并且在控制台应用程序上生成板的地步。 但是当玩家选择一个字符(X 或 O)时,我得到“System.FormatException:'输入字符串的格式不正确。”

我知道我需要使用 TryParse 但不确定如何在此示例中使用它

do
{
    board.GameBoard();
    Console.WriteLine("\n");
    if (chance == 0)
    {
        Console.Write(playerOne.Name + " turn, make your selection: ");
    }
    else if (chance % 2 == 1)
    {
        Console.Write(playerTwo.Name + " turn, make your selection: ");
    }
    Console.WriteLine("\n");

    // Code fails on the line below
    int choice = Convert.ToInt32(Console.ReadLine());

System.FormatException: '输入字符串的格式不正确。'

这可能工作吗?:

string choice = Console.ReadLine();
int choiceValue; 

  bool success = Int32.TryParse(choice , out choiceValue);

  if(success){
    // it was a number then do an operation
  }
  else{
   // was not a number do other operation
}

可以在这里阅读 tryparse

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM