问题描述
除了使用 #columns = ['a','b','c','d','e']
语句之外,还有什么方法可以捕获格式异常吗?如果用户输入的内容超过单个字符,则会出现格式异常。这是我的代码:
try-catch
解决方法
与其依赖控制流的异常,您应该始终首先尝试避免它们。在您的情况下,您可以使用 Read
而不是 ReadLine
来实现。因此,您只能读取一个字符:
Console.WriteLine("Would you like to play RPS? y/n");
char playOrNot = Convert.ToChar(Console.Read());
while(!validateChoice(playOrNot))
{
Console.WriteLine("Invalid! please re-enter selection");
playOrNot = Convert.ToChar(Console.Read());
}
,
有多种选择。
1 改用字符串:
public void Menu()
{
Console.WriteLine("Would you like to play RPS? y/n");
string playOrNot = Console.ReadLine();
while(!validateChoice(playOrNot))
{
Console.WriteLine("Invalid! please re-enter selection");
playOrNot = Console.ReadLine();
}
if (playOrNot.ToUpper() == "Y")
{
Console.Clear();
PlayGame();
}
}
public bool validateChoice(string playornot)
{
return !"YN".Contains(playOrNot);
}
2 使用 Console.ReadKey:
public void Menu()
{
Console.WriteLine("Would you like to play RPS? y/n");
char playOrNot = Console.ReadKey();
while(!validateChoice(playOrNot))
{
Console.WriteLine("Invalid! please re-enter selection");
playOrNot = Console.ReadKey();
}
if (char.ToUpper(playOrNot) == 'Y')
{
Console.Clear();
PlayGame();
}
}
public bool validateChoice(char playornot)
{
return !"YN".Contains(char.ToUpper(playOrNot));
}
3 使用简单的方法从 ReadLine 中获取字符:
public void Menu()
{
Console.WriteLine("Would you like to play RPS? y/n");
char playOrNot = GetChar();
while(!validateChoice(playOrNot))
{
Console.WriteLine("Invalid! please re-enter selection");
playOrNot = Console.GetChar();
}
if (char.ToUpper(playOrNot) == 'Y')
{
Console.Clear();
PlayGame();
}
}
public bool validateChoice(char playornot)
{
return !"YN".Contains(char.ToUpper(playOrNot));
}
public char GetChar()
{
string line = Console.ReadLine();
if (line.Length == 1)
return line[0]; // first char of line
return (char)0;
}