Option yes/no C# Console

后端 未结 6 1424
暗喜
暗喜 2021-01-15 01:15

I\'m creating a C# program for the Currency Converter by console. At the end I would to insert \"Continue? (yes/no)\". Here the user have to chose. I\'ve tried this but it

6条回答
  •  生来不讨喜
    2021-01-15 01:42

            float Dollaro = 1.32f, Euro, Cambio;
            string EuroStr;
            ConsoleKeyInfo risposta;
            do
            {
                Console.Write ( "Euro: " );
                EuroStr = Console.ReadLine ();
                bool result = Single.TryParse ( EuroStr, out Euro );
                if ( result )
                {
                    Cambio = Dollaro * Euro;
                    Console.WriteLine ( "Dollaro: " + Cambio );
                } else {
                    Console.WriteLine ( "Please enter a number" );
                }
                bool check = false;
                do {
                    Console.Write ( "\nVuoi continuare? (yes/no) " );
                    risposta = Console.ReadKey ( true );
                    check = !( ( risposta.Key == ConsoleKey.Y ) || ( risposta.Key == ConsoleKey.N ) );
                } while ( check );
                switch ( risposta.Key )
                {
                    case ConsoleKey.Y: Console.WriteLine ( "Yes" ); break;
                    case ConsoleKey.N: Console.WriteLine ( "No" ); break;
                } 
            } while ( risposta.Key != ConsoleKey.N );
    

    I've changed some things:

    • if I enter a character for the Euro - FormatException msdn. So I've added a TryParse();
    • I've changed the response from string to ConsoleKeyInfo msdn - this makes the check for "Y" or "N" easier and I think clearer, and there is no need to cast the user input with ToLower() msdn and compare it with a string;
    • also a check if the user presses "Y" or "N", while the input is different, the same message will appear - Console.Write ( "\nVuoi continuare? (yes/no) " );

    In general you should filter all data\info ( whatever ) comes from the user, to avoid exception.

提交回复
热议问题