我只想要0或1 ...如果我写2个或更多我希望程序抛出异常...我怎么才能接受这2个数字?
while (true)
{
try
{
Console.WriteLine("BET OR PASS? (BET == 0 / PASS == 1)");
int n = int.Parse(Console.ReadLine());
return n;
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("Invalid Ans!! try again");
Console.ForegroundColor = ConsoleColor.Gray;
}
}
答案 0 :(得分:4)
如果您只想要0
或1
只读一个字符:
var key = Console.ReadKey(false); // this read one key without displaying it
if (key.Key == ConsoleKey.D0)
{
return 0;
}
if (key.Key == ConsoleKey.D1)
{
return 1;
}
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("Invalid Ans!! try again");
Console.ForegroundColor = ConsoleColor.Gray;
答案 1 :(得分:2)
您不应该使用控制流的例外。使用TryParse
重写:
while (true)
{
Console.WriteLine("BET OR PASS? (BET == 0 / PASS == 1)");
int n;
bool isOk = int.TryParse(Console.ReadLine(), out n);
if(isOk && n >= 0 && n <= 1)
{
return n;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("Invalid Ans!! try again");
Console.ForegroundColor = ConsoleColor.Gray;
}
}
答案 2 :(得分:0)
在尝试中你可以像这样抛出;
try
{
Console.WriteLine("BET OR PASS? (BET == 0 / PASS == 1)");
int n = int.Parse(Console.ReadLine());
if (n != 0 || n != 1)
throw new InvalidArgumentException();
return n;
}
基本上,无论如何阅读输入,然后再检查。如果它不是1或0,则抛出无效的参数异常。这实际上会被你的catch块捕获,但是一旦你认识到错误取决于你就想做什么。如果你真的希望程序像你说的那样崩溃然后删除catch,你的程序将随时崩溃并抛出异常。
答案 3 :(得分:0)
while (true)
{
Console.WriteLine("BET OR PASS? (BET == 0 / PASS == 1)");
int n;
if(!int.TryParse(Console.ReadLine(), out n))
{
n = -1;
}
if(n == 0 || n == 1)
{
return n;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("Invalid Ans!! try again");
Console.ForegroundColor = ConsoleColor.Gray;
}
}