控制台(输入字符串格式不正确)

时间:2015-03-28 02:32:33

标签: c#

大家好,所以我开始学习C#,当我试图混淆时,我想出了这个问题

它表示“输入字符串格式不正确” n = Convert.ToInt32(Console.ReadLine());

这是整个代码

namespace Exercise13
{
    class Program
    {
        static void Main(string[] args)
        {
            char choice;
            Console.Write("What operation would you like to use?");
            Console.WriteLine("\na. Addition \tb. Subtraction \tc.Multiplication \td.Division");
            choice = (char)Console.Read();
            if (choice == 'a')
            {
                sumValues();
            }
            else if (choice == 'b') 
            {
                minusValues();
            }
            else if (choice == 'c') 
            {
                timesValues();
            }
            Console.ReadLine();

        }
        static void sumValues() 
        {


            int n = 0;
            int sum = 0;
            int i = 0,val = 0;
            Console.Write("How many numbers do you want calculate: ");
            n = Convert.ToInt32(Console.ReadLine());            

            for (i = 0; i < n; i++) 
            {
                Console.Write("\nInput number: ");
                val = Convert.ToInt32(Console.ReadLine());
                sum += val;

            }
            Console.Write("\nThe Answer is: "+sum);

        }
        static void minusValues() 
        {
            int diff = 0, m, z, value;
            Console.Write("How many numbers do you want calculate: ");
            m = int.Parse(Console.ReadLine());
            for (z = 0; z < m; z++)
            {
                Console.Write("\nInput number: ");
                value = int.Parse(Console.ReadLine());
                diff -= value;

            }
            Console.Write("\nThe Answer is: " + diff);

        }
        static void timesValues()
        {
            int prod = 0, e, i, val;
            Console.Write("How many numbers do you want to calculate: ");
            e = Convert.ToInt32(Console.ReadLine());
            for (i = 0; i < e; i++) 
            {
                Console.Write("\nInput number: ");
                val = int.Parse(Console.ReadLine());
                prod *= val;
            }
            Console.Write("\nThe answer is: " + prod);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用Integer.TryParse来处理可能不是数字的字符串。然后提示用户输入是否无法解析以输入有效输入。

如果字符串不是确切的数字,则转换和解析都会抛出异常。

https://msdn.microsoft.com/en-us/library/f02979c7%28v=vs.110%29.aspx

        int n = 0;
        int sum = 0;
        int i = 0,val = 0;
        Console.Write("How many numbers do you want calculate: ");
        var isValidNumber = Int32.TryParse(Console.ReadLine(), out n);
        if(!isValidNumber) {
            Console.WriteLine("Invalid number entered!");
        }
        else {
           //Use the number
        }