1
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?

4

5 回答 5

3

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());
}
于 2013-08-21T10:29:29.673 回答
1

I think you need to put the:

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

Inside a try-catch block.

Good luck.

于 2013-08-21T10:18:16.580 回答
1
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);
    }
}

}

于 2013-08-21T10:22:00.177 回答
1

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.
            }


        }
    }
}
于 2013-08-21T10:23:20.410 回答
0

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
}       
于 2013-08-21T10:36:57.177 回答