хочу, чтобы в моих выходных данных было сообщение об ошибке, когда пользователь пытается ввести десятичную дробь, и сообщение об ошибке, если пользователь пытается ввести любую строку, отличную от выхода

#c#

Вопрос:

 using System;

namespace LabExer2_CMS
{
    class Program
    {
        double fnum;
        double snum;
        double answer;
        string str;
        static void Main(string[] args)
        {
            double fnum;
            double snum;
            double answer;
            string str;

            Console.WriteLine("CALCULATOR");
            Console.WriteLine(" ");

            Console.WriteLine("First Number: ");
            fnum = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Select an operator: ( , -, * )");
            str = Console.ReadLine();

            Console.WriteLine("Second Number: ");
            snum = Convert.ToInt32(Console.ReadLine());

            if (str == " ")
            {
                answer = fnum   snum;
                Console.WriteLine("The answer is: " answer);
            }
            if (str == "-")
            {
                answer = fnum - snum;
                Console.WriteLine("The answer is: " answer);
            }
            if (str == "*")
            {
                answer = fnum * snum;
                Console.WriteLine("The answer is: "   answer);
            }

            Console.Write("PRESS ENTER TO EXIT");
            Console.ReadKey();


            
        }
    }
}
 

Комментарии:

1. Вместо использования Convert.ToInt32 используйте int.TryParse

2. Я хочу, чтобы слово «Ошибка» появлялось, если пользователь вводит десятичное или строковое значение, отличное от «Выход».

Ответ №1:

Первый ответ лучше, но если его трудно понять, вы можете попробовать этот. Вы можете обернуть строки Console.ReadLine() try {} catch {} оператором in, затем вам нужно инициализировать fnum и snum при их объявлении. И вам также следует проверить оператора.

 static void Main(string[] args)
        {
            double fnum = 0;
            double snum = 0;
            double answer;
            string str;

            Console.WriteLine("CALCULATOR");
            Console.WriteLine(" ");

            Console.WriteLine("First Number: ");

            try
            {
                fnum = Convert.ToInt32(Console.ReadLine());
            }
            catch
            {
                Console.WriteLine("Error!");
                return;
            }

            Console.WriteLine("Select an operator: ( , -, * )");
            str = Console.ReadLine();
            if (str != " " amp;amp; str != "-" amp;amp; str != "*")
            {
                Console.WriteLine("Wrong operator!");
                return;
            }

            Console.WriteLine("Second Number: ");

            try
            {
                snum = Convert.ToInt32(Console.ReadLine());
            }
            catch
            {
                Console.WriteLine("Error!");
                return;
            }

            if (str == " ")
            {
                answer = fnum   snum;
                Console.WriteLine("The answer is: "   answer);
            }
            if (str == "-")
            {
                answer = fnum - snum;
                Console.WriteLine("The answer is: "   answer);
            }
            if (str == "*")
            {
                answer = fnum * snum;
                Console.WriteLine("The answer is: "   answer);
            }

            Console.Write("PRESS ENTER TO EXIT");
            Console.ReadKey();
        }
 

Ответ №2:

если это вам поможет

 

using System;

namespace LabExer2_CMS
{
    class Program
    {
        double fnum;
        double snum;
        double answer;
        string str;
        
        /// <summary>
        /// Used instead of the original:
        /// 
        /// Console.WriteLine("First Number: ");
        /// fnum = Convert.ToInt32(Console.ReadLine());
        ///  
        /// resp.
        ///  
        /// Console.WriteLine("Second Number: ");
        /// snum = Convert.ToInt32(Console.ReadLine());
        /// 
        /// </summary>
        static double getDouble(string msg) {

            double res = 0;
            string input = "";
            bool isOk = false;
            
            while (!isOk) {
                
              Console.WriteLine(msg);
              input = Console.ReadLine();
              isOk = double.TryParse(input, out res);
              
              if(!isOk) { Console.WriteLine("Invalid input."); }
              
            }
            
            return res;
            
        }
        
        /// <summary>
        /// Used instead of the original:
        ///             
        /// Console.WriteLine("Select an operator: ( , -, * )");
        /// str = Console.ReadLine();
        /// 
        /// </summary>
        static string getOperator(string msg1, string[] operators) {
            
            string res = "";
            string input = "";
            bool isOk = false;
            string msg2 = String.Join(",", operators);
            string msg = msg1   "("   msg2   ") ";
            
            while (!isOk) {
                
              Console.WriteLine(msg);
              input = Console.ReadLine();
              isOk = Array.IndexOf(operators, input) >= 0;
              
              if(!isOk) { Console.WriteLine("Invalid input."); }
              
            }

            return res;
             
        }
        
        static void Main(string[] args)
        {
            double fnum;
            double snum;
            double answer;
            string str;

            Console.WriteLine("CALCULATOR");
            Console.WriteLine(" ");

            fnum = getDouble("First Number: ");

            string[] operators = new string [] {" ", "-", "*"};
            str = getOperator("Select an operator: ", operators);

            snum = getDouble("Second Number: ");

            if (str == " ")
            {
                answer = fnum   snum;
                Console.WriteLine("The answer is: " answer);
            }
            if (str == "-")
            {
                answer = fnum - snum;
                Console.WriteLine("The answer is: " answer);
            }
            if (str == "*")
            {
                answer = fnum * snum;
                Console.WriteLine("The answer is: "   answer);
            }

            Console.Write("PRESS ENTER TO EXIT");
            Console.ReadKey();

        }
    }
}