如何使用字符.使用字符串尝试解析
本文关键字:字符串 何使用 字符 | 更新日期: 2023-09-27 18:31:34
我创建了一个播放器类,并从该类为我的菜单驱动的播放器系统创建了一个数组 我正在尝试使用我的 GetChar 方法来继续显示提示并读取用户在键盘上键入的任何内容,直到 Char.TryParse 可以将输入转换为字符 但是我不断收到错误 当我调用我的 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;
}
查看您的代码实现,您似乎正在专门调用GetChar
函数来获取字符串输入。但是,您的函数一次只能返回 1 个字符。当您尝试将字符直接转换为字符串时,您会收到该错误。我相信这不是你想要的。如果您将 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;
}
由于字符串可以是任意数量的字符,因此不能将其隐式转换为char
。您需要将此部分input.Key.ToString()
更改为input.KeyChar
或执行类似操作input.Key.ToString().ToCharArray()[0]