C# testing to see if a string is an integer?

后端 未结 10 1438
北恋
北恋 2020-11-28 12:00

I\'m just curious as to whether there is something built into either the C# language or the .NET Framework that tests to see if something is an integer

if (x         


        
10条回答
  •  心在旅途
    2020-11-28 12:07

    I've been coding for about 2 weeks and created a simple logic to validate an integer has been accepted.

        Console.WriteLine("How many numbers do you want to enter?"); // request a number
        string input = Console.ReadLine(); // set the input as a string variable
        int numberTotal; // declare an int variable
    
        if (!int.TryParse(input, out numberTotal)) // process if input was an invalid number
        {
            while (numberTotal  < 1) // numberTotal is set to 0 by default if no number is entered
            {
                Console.WriteLine(input + " is an invalid number."); // error message
                int.TryParse(Console.ReadLine(), out numberTotal); // allows the user to input another value
            }
    
        } // this loop will repeat until numberTotal has an int set to 1 or above
    

    you could also use the above in a FOR loop if you prefer by not declaring an action as the third parameter of the loop, such as

        Console.WriteLine("How many numbers do you want to enter?");
        string input2 = Console.ReadLine();
    
        if (!int.TryParse(input2, out numberTotal2))
        {
            for (int numberTotal2 = 0; numberTotal2 < 1;)
            {
                Console.WriteLine(input2 + " is an invalid number.");
                int.TryParse(Console.ReadLine(), out numberTotal2);
            }
    
        }
    

    if you don't want a loop, simply remove the entire loop brace

提交回复
热议问题