我是一名正在学习.NET 的初学者。
我尝试在控制台读取行中解析我的整数,但它显示格式异常。
My code:
using System;
namespace inputoutput
{
class Program
{
static void Main()
{
string firstname;
string lastname;
// int age = int.Parse(Console.ReadLine());
int age = Convert.ToInt32(Console.ReadLine());
firstname = Console.ReadLine();
lastname=Console.ReadLine();
Console.WriteLine("hello your firstname is {0} Your lastname is {1} Age: {2}",
firstname, lastname, age);
}
}
}
如果抛出格式异常,则意味着输入无法解析为int
。您可以使用类似的方法更有效地检查这一点int.TryParse()
。例如:
int age = 0;
string ageInput = Console.ReadLine();
if (!int.TryParse(ageInput, out age))
{
// Parsing failed, handle the error however you like
}
// If parsing failed, age will still be 0 here.
// If it succeeded, age will be the expected int value.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)