2014-11-22 160 views
0

我創建了一個玩家類併爲該菜單驅動的玩家系統創建了一個數組我試圖用我的GetChar方法繼續顯示提示符並閱讀用戶在鍵盤上鍵入的內容直到Char.TryParse可以將輸入轉換成字符,但我不斷收到錯誤不能將類型字符轉換爲字符串

無法含蓄轉換char類型爲字符串

,當我打電話給我的GetChar方法。

任何幫助,將不勝感激

// Creates a player in the tables if the array is not already full and the name is not a duplicate 
static void ProcessCreate(Int32 number, String firstName, String lastName, Int32 goals, 
     Int32 assists, Player[] players, ref Int32 playerCount, Int32 MAXPLAYERS) 
{ 
     //Int32 player = 0; 
     if (playerCount < MAXPLAYERS) 
     { 
      number = IOConsole.GetInt32("\nCreate Player: please enter the player's number"); 
         //Console.ReadLine(); 
      if (GetPlayerIndex(number, firstName, lastName, goals, assists, players, ref playerCount) == -1) 
      { 
       firstName = IOConsole.GetChar("\nCreate Player: please enter the player's First Name"); 
        //Console.ReadLine(); 
        lastName = IOConsole.GetChar("\nCreate Player: please enter the player's Last Name"); 
       //Console.ReadLine(); 
       goals = IOConsole.GetInt32("\nCreate Player: please enter the player's goals"); 
       Int32.Parse(Console.ReadLine()); 
       assists = IOConsole.GetInt32("\nCreate Player: please enter the player's assists"); 
       //Console.ReadLine(); 
       InsertPlayer(number, firstName, lastName, goals, assists, players, ref playerCount); 
       Console.WriteLine("\n{0,7} {1,-20}{2, -20}{3,8}{4,8}{5,8}\n", "Number", "First Name", "Last Name", "Goals", " Assists", "Points"); 
       for (Int32 player = 0; player < playerCount; player++) 
       Console.WriteLine("{0,7} {1,-20}{2, -20}{3,8}{4,8}{5,8}", 
       players[player].Number, players[player].FirstName, players[player].LastName, 
       players[player].Goals, players[player].Assists, players[player].Points()); 

       Console.WriteLine(); 
      } 
      else 
       Console.WriteLine("\nCreate Player: the player number already exists"); 
     } 
     else 
      Console.WriteLine("\nCreate Player: the player roster is already full"); 
    } 

這裏是我GetChar方法

public static char GetChar(String prompt) 
{ 
     // declare variables 
     char validChar; 

     while (!Char.TryParse(Console.ReadLine(), out validChar)) 
     { 
      Console.WriteLine("Invalid entery - try again."); 
      Console.Write(prompt); 
     } 

     return validChar; 
} 

回答

2
while (!Char.TryParse(Console.ReadLine(), out validChar)) 

在這一行你正在閱讀的字符串數據,而不是單個字符,所以你不能分配它到'validChar'(方法Console.ReadLine)。 嘗試將此方法的調用分配給字符串變量,然後使用index []運算符獲取第一個字符。

或者您可以使用

public static ConsoleKeyInfo ReadKey() 
相關問題