Console.Read() and Console.ReadLine() FormatExcept

2019-07-25 17:20发布

问题:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Int32 a = 3;
            Int32 b = 5;

            a = Console.Read();

            b = Convert.ToInt32(Console.ReadLine());

            Int32 a_plus_b = a + b;
            Console.WriteLine("a + b =" + a_plus_b.ToString());
        }
    }
}

I get an error message at the ReadLine() function:

FormatException was unhandled.

What is the problem?

回答1:

I guess it is just because you pressing ENTER key after you type first number. Lets analyze your code. Your code reads the first symbol you entered to a variable that Read() function does. But when you press enter key ReadLine() function returns empty string and it is not correct format to convert it to integer.

I suggest you to use ReadLine() function to read both variables. So input should be 7->[enter]->5->[enter]. Then you get a + b = 12 as result.

static void Main(string[] args)
{
    Int32 a = 3;
    Int32 b = 5;

    a = Convert.ToInt32(Console.ReadLine());
    b = Convert.ToInt32(Console.ReadLine());

    Int32 a_plus_b = a + b;
    Console.WriteLine("a + b =" + a_plus_b.ToString());
}


回答2:

I think you need to put the:

b = Convert.ToInt32(Console.ReadLine());

Inside a try-catch block.

Good luck.



回答3:

What you want to do is to use try catch, so if someone puts in something wrong you can find out

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Int32 a = 3;
            Int32 b = 5;

            a = Console.Read();
            try
            {
                b = Convert.ToInt32(Console.ReadLine());
                Int32 a_plus_b = a + b;
                Console.WriteLine("a + b =" + a_plus_b.ToString());
            }
            catch (FormatException e)
            {
                // Error handling, becuase the input couldn't be parsed to a integer.
            }


        }
    }
}


回答4:

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        Int32 a = Convert.ToInt32(Console.ReadLine());
        Int32 b = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("a + b = {0}", a + b);
    }
}

}



回答5:

You can try this:

Int32 a = 3;
Int32 b = 5;

if (int.TryParse(Console.ReadLine(), out a))
{
    if (int.TryParse(Console.ReadLine(), out b))
    {
        Int32 a_plus_b = a + b;
        Console.WriteLine("a + b =" + a_plus_b.ToString());
    }
    else
    {
         //error parsing second input
    }
}
else 
{
     //error parsing first input
}