Convert.ToInt32(Console.ReadLine())输入字符串的格式不正确

时间:2019-03-02 08:30:18

标签: c# input

嗨,我正在尝试学习C#,我已经知道其他一些编程语言,例如C和Java,但是当我在控制台中运行代码时,我似乎无法制作出这种简单的计算器,我似乎得到了“输入字符串为格式不正确”,然后程序终止,我将在出现错误的代码行中留下注释。

using System;

namespace csharp2
{

    class Program
    {

        static void Main(string[] args)
        {
            int n1, n2, sum = 0, counter = 0;
            char opp;

            Console.WriteLine("Enter expression 2 numbers and 1 operators at a time\n ");


            while (true)
            {

                if (counter == 0)
                {
                    n1 = askNumber();
                    opp = askOperator();
                    if (isOpp(opp) == false)
                        break;
                    n2 = askNumber();
                    sum = calculate(n1, opp, n2);
                    ++counter;
                }
                else
                {
                    Console.Write("Sum = " + sum);
                    opp = askOperator();
                    if (isOpp(opp) == false)
                        break;
                    n2 = askNumber();
                    sum = calculate(sum, opp, n2);

                }
            }
            Console.WriteLine("Final Sum = " + sum);
            Console.ReadLine();
        }

        static int askNumber()
        {
            return Convert.ToInt32(Console.ReadLine()); //******** ERROR HERE "Input String was not in correct format" *********

        }
        static char askOperator()
        {
            return Console.ReadKey().KeyChar;
        }
        static bool isOpp(char opp)
        {
            switch (opp)
            {
                case '+':
                case '-':
                case '*':
                case '/': return true;
                default: return false;
            }
        }
        static int calculate(int n1, char opp, int n2)
        {
            switch (opp)
            {
                case '+': return n1 + n2;
                case '-': return n1 - n2;
                case '*': return n1 * n2;
                default: return n1 / n2;

            }
        }
    }
}

0 个答案:

没有答案