我为我的菜单驱动的播放器系统创建了一个播放器类并从该类创建了一个数组我试图使用我的GetChar方法继续显示提示并读取键盘上用户输入的内容,直到Char.TryParse可以转换为输入到char但我一直得到错误当我调用我的GetChar方法时,不能隐式地将类型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)
{
string message;
//Int32 player = 0;
if (playerCount < MAXPLAYERS)
{
try
{
message = ("\nCreate Player: please enter the player's number");
number = IOConsole.GetInt32(message);
//(Console.ReadLine());
}
catch (Exception)
{
Console.WriteLine("Number Must Be Postive");
}
if (GetPlayerIndex(number, firstName, lastName, goals, assists, players, ref playerCount) == -1)
{
message =("\nCreate Player: please enter the player's First Name");
firstName = IOConsole.GetChar(message);
//Console.ReadLine();
message = ("\nCreate Player: please enter the player's Last Name");
lastName = IOConsole.GetChar(message);
//Console.ReadLine();
message =("\nCreate Player: please enter the player's goals");
try
{
goals = IOConsole.GetInt32(message);
//Int32.Parse(Console.ReadLine());
message = ("\nCreate Player: please enter the player's assists");
assists = IOConsole.GetInt32(message);
//Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("Number Must Be Postive");
}
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)
{
char validChar;
var input = Console.ReadKey();
while (!Char.TryParse(input.Key.ToString(), out validChar))
{
Console.WriteLine("Invalid entry - try again.");
Console.Write(prompt);
}
return validChar;
}
答案 0 :(得分:0)
由于字符串可能是任意数量的字符,因此您无法将其隐式地转换为char
。您需要将此部分input.Key.ToString()
更改为input.KeyChar
或执行此类input.Key.ToString().ToCharArray()[0]
答案 1 :(得分:0)
查看您的代码实现,似乎您专门调用GetChar
函数来获取字符串输入。但是,您的功能一次只能返回1个字符。当您尝试将char直接转换为字符串时,您会收到该错误。我相信这不是你想要的。如果您使用以下内容替换GetChar代码,那应该适合您:
public static string GetString(string prompt)
{
var input = Console.ReadLine();
while (string.IsNullOrWhiteSpace(input))
{
// you may also want to do other input validations here
Console.WriteLine("Invalid entry - try again.");
Console.Write(prompt);
input = Console.ReadLine();
}
return input;
}