Reputation: 59
I'm still learning c# and came across this problem , i wanted to make a program that make sure that the user enters an integer . but when i do this , i'm stuck in an infinite loop . Why the the bool b; variable change its value in catch block even if the user typed an integer ? My code :
class MainClass
{
public static void Main (string[] args)
{
int n= 0;
bool b = true;
do {
try {
Console.WriteLine ("Enter an integer : ");
n = Convert.ToInt32 (Console.ReadLine ());
} catch (Exception e) {
Console.WriteLine (e.Message);
b = false;
} finally {
Console.WriteLine (n);
}
} while(b == false);
}
}
but i fixed the problem when i did this :
class MainClass
{
public static void Main (string[] args)
{
int n= 0;
bool b;
do {
try {
b = true;
Console.WriteLine ("Enter an integer : ");
n = Convert.ToInt32 (Console.ReadLine ());
} catch (Exception e) {
Console.WriteLine (e.Message);
b = false;
} finally {
Console.WriteLine (n);
}
} while(b == false);
}
}
can someone explain please ?
Upvotes: 0
Views: 592
Reputation: 1651
The b variable is trapped as false forever, if the user doesn't enter a correct input. So, in the beginning of every loop the boolean variable needs to be set as "true" which was its default value. That is because every iteration should be a new try for the user to enter an integer.
Upvotes: 4
Reputation: 4341
You can easily do this just by using int.TryParse without a try catch block
static void Main (string[] args)
{
int n= 0;
bool b;
do {
Console.Write ("Enter an integer : ");
b = int.TryParse(Console.ReadLine (), out n);
} while(!b);
//int has been entered, now do something else...
}
You can simplify it even further by not even introducing the bool variable
static void Main (string[] args)
{
int n;
do {
Console.Write ("Enter an integer : ");
} while(!int.TryParse(Console.ReadLine (), out n));
//int has been entered, now do something else...
}
Upvotes: 2