选项是/否C#控制台 [英] Option yes/no C# Console

查看:46
本文介绍了选项是/否C#控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过控制台为Currency Converter创建一个C#程序.最后,我要插入继续?(是/否)".用户必须在这里进行选择.我已经尝试过了,但是没用

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 doesn't work

float Dollaro = 1.32f, Euro;
float Cambio;
string EuroStr;


        Console.Write("Euro: ");
        EuroStr = Console.ReadLine();
        Euro = float.Parse(EuroStr);

        Cambio = Dollaro * Euro;

        Console.WriteLine("Dollaro: " + Cambio);
        Console.WriteLine("Vuoi continuare? (yes/no)");
        Console.ReadLine();
        string risposta = Console.ReadLine();
        do
        {
            if (risposta.Equals("Y"))
            {
                Console.WriteLine("Yes");
                break;
            }
            else if (risposta.Equals("N"))
            {
                Console.WriteLine("No");
                break;
            }

        } while (risposta == "N");

推荐答案

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

我更改了一些内容:

  • 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) " );

通常,您应该过滤掉所有来自用户的data \ info(无论如何),以避免出现异常.

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

这篇关于选项是/否C#控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆