C#:如何为这段代码编写另一个函数?

时间:2013-10-05 12:44:50

标签: c#

如何为此代码编写另一个名为noNegatives的函数?我想用另一个名为noNegatives的函数重写代码,但我仍然希望程序做同样的事情。

    class Program
    {
        static void Main(string[] args)
        {
            string numberIn;
            int numberOut;

            numberIn = Console.ReadLine();

            while (!int.TryParse(numberIn, out numberOut) || numberOut < 0)
            {
                Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
                numberIn = Console.ReadLine();
            }
        }       
    }

3 个答案:

答案 0 :(得分:0)

Follwing是您编写它的最简单方法

static void Main(string[] args)
            {
                int retVal=0; 
                string numberIn;
                int numberOut;
                numberIn = Console.ReadLine();

                while(noNegatives(numberIn,numberOut)=0)
                {

                }
             } 

    int noNegatives(String numberIn,int numberOut)
    {


                numberIn = Console.ReadLine();

                if (!int.TryParse(numberIn, out numberOut) || numberOut < 0)
                {
                    Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
                    return 0;

                }
                else
                {
                   return 1;
                }
    }

答案 1 :(得分:0)

static void Main(string[] args)
{
    int number = NoNegatives();
}
static int NoNegatives()
{
    int numberOut;

    string numberIn = Console.ReadLine();

    while (!int.TryParse(numberIn, out numberOut) || numberOut < 0)
    {
        Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
        numberIn = Console.ReadLine();
    }
    return numberOut;
}

答案 2 :(得分:0)

此问题与发布here的问题非常相似。

    static void Main(string[] args)
    {
        string numberIn = Console.ReadLine();
        int numberOut;

        while(!IsNumeric(numberIn))
        {
            Console.WriteLine("Invalid.  Enter a number that's 0 or higher.");
            numberIn = Console.ReadLine();
        }
        numberOut = int.Parse(numberIn);
    }

    private static bool IsNumeric(string num)
    {
        return num.ToCharArray().Where(x => !Char.IsDigit(x)).Count() == 0;
    }

由于负号不是数字,因此对于负数,IsNumeric将返回false。