[英]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.