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

前端 未结 4 1435
既然无缘
既然无缘 2020-12-22 13:50

I\'m a beginner who is learning .NET.

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

My code:

using System;         


        
相关标签:
4条回答
  • 2020-12-22 14:24

    You can handle invalid formats except integer like this;

            int age;
            string ageStr = Console.ReadLine();
            if (!int.TryParse(ageStr, out age))
            {
                Console.WriteLine("Please enter valid input for age ! ");
                return;
            }
    
    0 讨论(0)
  • 2020-12-22 14:32

    Your code is absolutely correct but your input may not be integer so you are getting the errors. Try to use the conversion code in try catch block or use int.TryParse instead.

    0 讨论(0)
  • 2020-12-22 14:38

    You can convert numeric input string to integer (your code is correct):

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

    If you would handle text input try this:

    int.TryParse(Console.ReadLine(), out var age);
    
    0 讨论(0)
  • 2020-12-22 14:48

    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.
    
    0 讨论(0)
提交回复
热议问题