Reputation: 37
I am using TryParse for the code below, but when I put 1 or 2 the program doesnt continue.
int x = -1;
bool noRecords = true;
do
{
Console.WriteLine("1.Add Data");
Console.WriteLine("2.Show Data");
Console.WriteLine("0.Exit");
//x = Convert.ToInt32(Console.ReadLine());
if (x == 1)
{
Helper.ShowAddMenu(noRecords);
}
if (x == 2)
{
Helper.ShowDataMenu();
}
} //while (x != 0);
while (!int.TryParse(Console.ReadLine(), out x) || x > 2 || x < 0);
Upvotes: 0
Views: 241
Reputation: 12811
Your while
loop is wrong if you want it to continue when you enter 1
or 2
. The order of operations during execution of that expression in your while
loop will be:
1
Console.Readline()
will return the string "1"
int.TryParse("1", out x)
will set x to 1
and will return true
!true
evaluates to false
x > 2
evaluates to false
because x
is 1
x < 0
evaluates to false
because x
is 1
while(false || false || false)
EDIT: Given the discussion in the comments below, I believe OPs use case would be best served with a code structure more like the following. Trying to cram it all into the while
clause is going to be confusing.
static void Main()
{
ShowMenu();
while (true)
{
int x;
if (!int.TryParse(Console.Readline(), out x))
ShowMenu();
else if (x == 0)
break;
else if (x == 1)
Helper.ShowAddMenu(noRecords);
else if (x == 2)
Helper.ShowDataMenu();
}
}
static void ShowMenu()
{
Console.WriteLine("1.Add Data");
Console.WriteLine("2.Show Data");
Console.WriteLine("0.Exit");
}
Upvotes: 3
Reputation: 573
Change !int.TryParse
to just int.TryParse
. TryParse returns true on success, not false.
See here dotnetfiddle.net/6JCoPQ
Upvotes: 0