0

How would I write another function named noNegatives for this code? I want to rewrite the code with another function named noNegatives but I still want the program to do the same thing.

    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();
            }
        }       
    }
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
User
  • 159
  • 1
  • 3
  • 10
  • 2
    `void noNegatives(){}` fulfills what you've asked. What should the function do? – Tim S. Oct 05 '13 at 12:46
  • I want to rewrite the code with another function named noNegatives but I still want the program to do the same thing. – User Oct 05 '13 at 12:52

3 Answers3

0

Follwing is the simplest way you can write it

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;
                }
    }
C Sharper
  • 8,284
  • 26
  • 88
  • 151
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;
}
Tim S.
  • 55,448
  • 7
  • 96
  • 122
0

This question is very similar to the one posted 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;
    }

Since the negative sign is not a digit, IsNumeric will return false for negative numbers.

Community
  • 1
  • 1
John DeLeon
  • 305
  • 1
  • 3