2013-10-05 4 views
0

Как бы написать другую функцию с именем noNegatives для этого кода? Я хочу переписать код с помощью другой функции с именем noNegatives, но я все равно хочу, чтобы программа выполняла то же самое.C#: Как написать еще одну функцию для этого кода?

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(); 
      } 
     }  
    } 
+2

'void noNegatives() {}' выполняет то, что вы просили. Что должна делать эта функция? –

+0

Я хочу переписать код с помощью другой функции с именем noNegatives, но я все равно хочу, чтобы программа выполняла то же самое. – User

ответ

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; 
} 
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; 
       } 
    } 
+0

Как написано, ваш код не будет работать. Я бы пошел с подписью 'int noNegatives()'. –

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 для отрицательных чисел.

Смежные вопросы