如何使用console.readline()读取整数? [英] How to read an integer using console.readline()?

查看:844
本文介绍了如何使用console.readline()读取整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个正在学习.NET的初学者。

I'm a beginner who is learning .NET.

我尝试在控制台读取行中解析我的整数,但是它显示格式异常。

I tried parsing my integer in console readline but it shows a format exception.

我的代码:

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()之类的方法更有效地进行检查。例如:

If it's throwing a format exception then that means the input isn't able to be parsed as an int. You can check for this more effectively with something like int.TryParse(). For example:

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.

这篇关于如何使用console.readline()读取整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆