Вопрос

I only want 0 or 1... if i write 2 or more I want the program to throw an exception ... how can i only accept this 2 numbers?

 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;
            }
        }
Это было полезно?

Решение 2

You shouldn't use exceptions for control flow. Rewrite using 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;
    }
}

Другие советы

If you want only 0 or 1 read only one char:

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;

Take a look at Console.ReadKey.

Inside the try you can just throw like this;

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;
}

basically, read the input no matter what, check it afterwards. If it's not a 1 or a 0 then you throw and invalid argument exception. That will actually be caught by your catch block but what you want to do once you recognize the error is up to you. If you really want the program to crash like you say then remove the catch and your program will crash anytime and exception is thrown.

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;
         }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top