本文介绍了Console.Read()和Console.ReadLine()FormatException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 使用系统; 

命名空间ConsoleApplication1
{
类程序
{
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()函数:

div>

我想这只是因为在输入第一个数字后按ENTER键。
让我们分析你的代码。您的代码读取您输入的变量 Read()的第一个符号。但是当你按下回车键 ReadLine()函数返回空字符串,并且格式不正确将其转换为整数。



我建议你使用 ReadLine()函数来读取这两个变量。因此输入应该是 7-> [enter] - > 5-> [enter] 。然后你得到 a + b = 12 作为结果。

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


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:

What is the problem?

解决方案

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

这篇关于Console.Read()和Console.ReadLine()FormatException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:45