Thursday, 5 September 2013

unreachable code visual studio c# do while loop

unreachable code visual studio c# do while loop

i am attempting to write code (in visual studio 2012 using c#) that will
allow a user to select an account using 1,2,3 or 4. i am using a do-while
loop so i can use 0 to exit (break?) or run the loop again until a valid
option is selected.
The problem is, Visual studio is telling me the code validAccount = true;
is unreachable, and won't let me test it. since this method should also
return a value i have a "not all code paths return a value" error, and i
am getting really confused. here is my code:
static int chooseAccount() {
bool validAccount = false;
do {
Console.Clear();
Console.WriteLine("Select an Account: \r\n 1: Savings \r\n 2:
Debit \r\n 3: Credit \r\n 4: Investment");
int inputNumber = int.Parse(Console.ReadLine()); //by
declaring int inputNumber here we save having an extra line.
if ((inputNumber >= 1) && (inputNumber <= 4)) {
return inputNumber;
validAccount = true;
}
else if (inputNumber == 0) {
break;
}
else {
Console.WriteLine("Error: please choose an account using
1, 2, 3, 4 or 0 to exit");
}
} while (!validAccount);
}//end chooseAccount
Maybe I've just been staring at this for too long and can't see the simple
mistake I've made. I welcome a fresh perspective or direction to where i
can find a solution, should this sort of problem have already been solved.
(it's kinda hard to google for something like "unreachable code" when the
code has to be so specific)

No comments:

Post a Comment