繁体   English   中英

如何使用console.readline()读取整数?

[英]How to read an integer using console.readline()?

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

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

我的代码:

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

您的代码绝对正确,但您的输入可能不是整数,因此您会收到错误消息。 尝试使用 try catch 块中的转换代码或使用 int.TryParse 代替。

您可以像这样处理除整数之外的无效格式;

        int age;
        string ageStr = Console.ReadLine();
        if (!int.TryParse(ageStr, out age))
        {
            Console.WriteLine("Please enter valid input for age ! ");
            return;
        }
Console.WriteLine("Enter number ");
int day = int.Parse(Console.ReadLine());

您可以将数字输入字符串转换为整数(您的代码是正确的):

int age = Convert.ToInt32(Console.ReadLine());

如果您要处理文本输入,请尝试以下操作:

int.TryParse(Console.ReadLine(), out var age);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM