C
CSharp-Jay
I am pretty new to csharp myself, but have been trying to do a few
things that I am running into problems with. I know there is a way
around it, but I just dont know what it is. I am hoping somebody here
can help me.
Here is a code example:
string sanswer = "";
int answer;
// have user choose an option
Console.WriteLine("\nPlease choose an option:");
Console.WriteLine("1. Yes");
Console.WriteLine("2. No");
sanswer = Console.ReadLine();
// sanity check sanswer and convert to int;
try
{
answer = int.Parse(sanswer);
}
catch
{
Console.WriteLine("There was an error! Please try again.");
Console.ReadKey();
Console.Clear();
Menu();
}
// this generates a compiler error when you use it
Console.WriteLine("You have chosen {0}", answer);
With this code, the compiler will return the error that I am
attempting to use an unassigned local variable 'answer'. But answer
NEEDS to be checked, else the user can type b as their choice to the
yes/no question. So, how do I get around this problem? - Jay
things that I am running into problems with. I know there is a way
around it, but I just dont know what it is. I am hoping somebody here
can help me.
Here is a code example:
string sanswer = "";
int answer;
// have user choose an option
Console.WriteLine("\nPlease choose an option:");
Console.WriteLine("1. Yes");
Console.WriteLine("2. No");
sanswer = Console.ReadLine();
// sanity check sanswer and convert to int;
try
{
answer = int.Parse(sanswer);
}
catch
{
Console.WriteLine("There was an error! Please try again.");
Console.ReadKey();
Console.Clear();
Menu();
}
// this generates a compiler error when you use it
Console.WriteLine("You have chosen {0}", answer);
With this code, the compiler will return the error that I am
attempting to use an unassigned local variable 'answer'. But answer
NEEDS to be checked, else the user can type b as their choice to the
yes/no question. So, how do I get around this problem? - Jay