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());
        }
    }
}

ReadLine()関数でエラー メッセージが表示されます。

FormatException は処理されませんでした。

何が問題ですか?

4

5 に答える 5

3

最初の number を入力した後に ENTER キーを押したからだと思います。コードを分析しましょう。コードは、関数がa変数に入力した最初のシンボルを読み取ります。Read()しかし、Enter キーを押すReadLine()と関数は空の文字列を返し、それを整数に変換するのは正しい形式ではありません。

ReadLine()function を使用して両方の変数を読み取ることをお勧めします。したがって、入力は7->[enter]->5->[enter]. その後a + b = 12、結果として得られます。

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

あなたがしたいことは、try catch を使用することです。

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 に答える
1

私はあなたが置く必要があると思います:

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

try-catchブロック内。

幸運を。

于 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 に答える