This following program will check whether value is provided or not in the Command Line Argument, if value is provided whether it is a numeric or not, if it is a numeric whether it is an odd or even.
I have a problem in how trueORfalse = int.TryParse(args[0], out n) behave.
We know inside the if condition if the expression is true that statement becomes o/p.
But in the program if a Command Line Argument is non-numeric though trueORfalse expression is false (Step Into (F11-key) will show the result) statement becomes o/p. How can this situation be explained? Problem is highlighted.
using System;
class Program
{
static void Main(string[] args)
{
int n ;
bool trueORfalse = false;
if(args.Length==0)
Console.WriteLine("Command Line Argument is not provided");
else
if (trueORfalse == int.TryParse(args[0], out n))
Console.WriteLine("Provid a numeric value");
else
if(n%2==0)
Console.WriteLine("Even");
else
Console.WriteLine("Odd");
Console.Read();
}
}
Loading
Posted Apr 29, 2014, 10:32 AM
VulpesPosted Apr 29, 2014, 10:16 AM
int n;
if (args.Length == 0)
{
Console.WriteLine("Command Line Argument is not provided");
}
else if (int.TryParse(args[0], out n))//NOT operator has been removed
{
if (n % 2 == 0)
Console.WriteLine("Even");
else
Console.WriteLine("Odd");
}
else
{
Console.WriteLine("Provide a numeric value");
}
It's now easier to see that the 'else if' clause is only entered if the command line argument is numeric.
Otherwise the code in the final 'else' clause is executed.
Posted Apr 29, 2014, 10:06 AM
using System;
class Program
{
static void Main(string[] args)
{
int n;
if (args.Length == 0)
Console.WriteLine("Command Line Argument is not provided");
else
if (int.TryParse(args[0], out n))//NOT operator has been removed
if (n % 2 == 0)
Console.WriteLine("Even");
else
Console.WriteLine("Odd");
else
Console.WriteLine("Provide a numeric value");
Console.Read();
}
}
Posted Apr 29, 2014, 9:19 AM
VulpesPosted Apr 29, 2014, 8:51 AM
Posted Apr 29, 2014, 8:27 AM
Normally the expression in if evaluated true only the statement belongs to that will be executed. How above contradiction can be explained.
VulpesPosted Apr 29, 2014, 7:18 AM
If it succeeds, the method returns true and the integer is returned in the second (output) parameter.
It is fails, the method returns false and a value of 0 is returned in the second parameter.
So, here, if a command line argument is provided, an attempt is made to parse it and if the attempt fails (i.e. the return value equals trueORfalse which is false), the user is asked to provide a numeric value. Otherwise the program goes on to print whether the number is odd or even.