문제

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