unreachable code visual studio c# do while loop - c#

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...)

The line with the error comes right after a return statement. Your code would, in every single case (and the compiler knows this), exit the function on the line before it, so it will never reach the next line.
You don't need to set validAccount to true to break the loop, because the return statement will exit the function, and therefore automatically exit the loop.
And finally, if you set validAccount to true and THEN return, no other function can access validAccount, so why did you need to bother setting it to true?
In truth, you don't need validAccount at all, because with your break and return statements you already control your way in and out of the loop. This will work:
static int chooseAccount() {
while(true) {
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());
if ((inputNumber >= 0) && (inputNumber <= 4)) {
return inputNumber;
}
else
{
Console.WriteLine("Error: please choose an account using 1, 2, 3, 4 or 0 to exit");
}
}
}

Please be aware that the return statement will take you out of the function immediately. Then the next validAccount = true; will never be executed!

Switch these two:
return inputNumber;
validAccount = true;

Related

How to return to a specific point int the code without having to use goto?

So I wrote a lottery program.
The program works as the following:
the user inputs 6 numbers ranging from 1 to 46.
the program chooses 6 numbers ranging from 1 to 46.
the program compares the arrays for matching numbers.
the program shows the user how many matching number he got right and also if he won the lottery or not.
end
now , I want to add an option to the user , if the user wants to try again he can just press Y and the program will jump him to the point where he inputs numbers.
But , I don't know how to achieve that without using goto, I don't want to use goto because I know it's bad practice to use it.
Would love to get some recommendations.
I know that I am still missing the N portion of the code, but I just wanted to show what I've tried so far.
char tryAgain;
if (gamelost || gamewon == true)
{
tryAgain = 'Y';
Console.WriteLine("Do you want to try again? Y/N");
tryAgain = char.Parse(Console.ReadLine());
if (tryAgain == 'Y')
{
goto gameAgain;
}
else
{
return;
}
}
}
Use a loop. You need to check the only condition upon which you exit the loop. Note that this code doesn't sanitize user's input.
using static System.Console;
void do_lottery()
{
while (true)
{
Write("Enter 6 digits, divided by comma: ");
var input = ReadLine();
var user_numbers = input.Split(",").Select(n => int.Parse(n));
var numbers_to_guess = new[] { 6, 23, 12, 46, 8, 2 };
if (user_numbers.All(n => numbers_to_guess.Any(z => z == n)))
{
WriteLine("You won!");
}
else
{
WriteLine("You lose!");
}
Write("Do you wanna play once again? (Y/N): ");
var answer = ReadLine().ToUpper();
if (answer != "Y") break; //Exit loop
}
WriteLine("Lottery finished.");
}

How to correctly implement while logic

I am writing a method to take user input for a menu with three options: 1,2,3. My do while loop runs, however my while logic is still accepting unwanted input. Why is my code not looping for inputs outside of my set range of values?
I have tried different logical operators, removing logical operators and setting while Option < Value.
private static MenuOption ReadUserOption()
{
int Option;
Console.WriteLine("Please make a selection");
Console.WriteLine("1, will run TestName, 2 will run Guess that number, 3 Wil quit the program.");
do
{
Option = Convert.ToInt32(Console.ReadLine());
return (MenuOption)(Option - 1);
} while (Option < 1 || Option > 3);
}
My goal is for any user input outside of <1 and >3 for the loop to continue until a value within that range is entered. In its current state if I enter 0 the loop will accept that value and output -1.
You just need to move the return statement outside the loop
private static MenuOption ReadUserOption()
{
int Option;
Console.WriteLine("Please make a selection");
Console.WriteLine("1, will run TestName, 2 will run Guess that number, 3 Wil quit the program.");
do
{
Option = Convert.ToInt32(Console.ReadLine());
} while (Option < 1 || Option > 3);
return (MenuOption)(Option - 1);
}

Application Not Working Correctly C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My code isn't storing a response as user input. It jumps to the else statement every time I get here. Then it throws the sum as 50? When I store input like Value of first number = 2 and value of second = 3.
I'm doing a class at home and I have been working for a few hours trying to figure out why my code doesn't work right.
C#, below:
Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
bool stopOrContinueAdding = true;
do
{
string inputMoreNumbers = Console.ReadLine();
switch (inputMoreNumbers.ToLower())
{
case "a":
inputMoreNumbers = "a";
stopOrContinueAdding = false;
break;
case "b":
inputMoreNumbers = "b";
stopOrContinueAdding = true;
break;
default:
stopOrContinueAdding = false;
break;
}
if (stopOrContinueAdding == false)
{
int sum = aNum.Sum();
Console.WriteLine("Here is the sum of your numbers: " + sum );
System.Threading.Thread.Sleep(4000);
Console.WriteLine("Redirecting to main menu...");
System.Threading.Thread.Sleep(2000);
Console.Clear();
Console.Write("Addition(a), Subraction(s), Multiplication(x), or Division(d)? ");
isInputValid = false;
}
else
{
Console.Clear();
Console.Write("Value of next number: ");
number++;
aNum[number - 1] = Convert.ToInt32(Console.Read());
Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
}
} while (stopOrContinueAdding != true) ;
I'm not entirely sure where I went wrong. I'd like to understand more :(
Thanks!
In your addition calculator, changing the following line:
aNum[number - 1] = Convert.ToInt32(Console.Read());
from Console.Read() to Console.ReadLine() seems to fix the issue. ReadLine() will block the execution until Enter is hit - Read() will not... So when you enter your second number and hit Enter, it executes your next ReadLine() statement (where you are expecting "a" or "b" depending on whether they want to continue) as a blank string.

Number Switch Statement

So I am trying to make this simple program, but using the switch statement when I run the program no matter what I put in, I always get the default answer. How can I make it to where it will choose the correct statement for the number I put in?
int number;
Console.WriteLine("Enter a number between 0 and 50: ");
number = int.Parse(Console.ReadLine());
switch (number )
{
case 1:
Console.WriteLine("Do you not know how to count? That's more than 50!");
break;
case 2:
Console.WriteLine("Did I say you could choose a number below 0?");
break;
default:
Console.WriteLine("Good job smarty pants!");
break;
}
Console.ReadLine();
Eh, just if and else if:
if (number > 50)
Console.WriteLine("Do you not know how to count? That's more than 50!");
else if (number < 0)
Console.WriteLine("Did I say you could choose a number below 0?");
else
Console.WriteLine("Good job smarty pants!");
Unfortunately, in this case you are trying to fit a tool to a use it was not designed for. The case is really for distinct cases over a solution space, not continuous ones. (The difference between the answer can be -1 or 1 and the answer can be < 0 and > 0). That being said, I support user Dmitry Bychenko's answer which states to use an if and else if to accomplish this task. I am sure you could devise a way to use a switch statement but it would be like using a hammer's back side to sand a floor.
Whats happening in your code is that the number you have read is unlikely to ever be 1 or 2 which is what will be compared. What you have currently converted to an if...else (which is easier to outline the problem with) would be:
if (number == 1)
{
Console.WriteLine("Do you not know how to count? That's more than 50!");
}
else if (number == 2)
{
Console.WriteLine("Did I say you could choose a number below 0?");
}
else
{
Console.WriteLine("Good job smarty pants!");
}
That should help you see what your actual issue is, although I will point it out that it appears you want to limit the user to a value between 0...50 but you are actually only checking that the number entered is equal to 1 or 2. You could use a switch statement for this type of problem but as you will still need to make sure the number is valid an if...else is slightly more efficient.
You also can try this:
int number = 12;
Dictionary<Func<int, bool>, Action> dict = new Dictionary<Func<int, bool>, Action>
{
{x => x < 0, () => Console.WriteLine("Smaller than 0")},
{x => x > 50, () => Console.WriteLine("Greater than 50")},
{x => (x >= 0 && x <= 50), () => Console.WriteLine("Between 0 and 50")}
};
dict.First(kvp => kvp.Key(number)).Value();

How to skip while in do while loop?

The problem is that I cant write do while loop without while part ... can I skip it somehow or .. ?
// 9. Keep adding numbers untill you add number 7 twice in a row .
int a;
int b;
do
{
Console.WriteLine("add number:");
a = int.Parse(Console.ReadLine());
Console.WriteLine("add number:");
b = int.Parse(Console.ReadLine());
if (a == 7 && b == 7)
{
break;
Console.WriteLine("end");
}
}
The best way to do this would be to have the condition in your while
while(a != 7 || b != 7)
{
Console.WriteLine("add number:");
a = int.Parse(Console.ReadLine());
Console.WriteLine("add number:");
b = int.Parse(Console.ReadLine());
}
Console.WriteLine("end");
This will make the loop automatically terminate when it finds that both values are 7
As per #AlexK's answer, you could also make the while have no condition, and just contain true
while(true)
{
Console.WriteLine("add number:");
a = int.Parse(Console.ReadLine());
Console.WriteLine("add number:");
b = int.Parse(Console.ReadLine());
if (a == 7 && b == 7)
{
break;
Console.WriteLine("end");
}
}
This will do the same as the above code, though instead of checking if the values are 7 at the beginning of each loop, it instead will loop infinitely until manually exited inside the loop
You may also notice that the syntax I have used is
while(/*condition*/)
{
//code here
}
This is a shorter version of the syntax that you are using, though it acts slightly differently. While the above code sample will never run any code if the condition isn't met when the loop is entered, the below code
do
{
//code here
}
while(/*condition*/);
Will always run the code contained inside the do at least once, regardless of whether the condition is met or not
You have two possibititles. Either set your condition directly to the while-part as Alfie already said or use an infinite loop. This is in particular usefull if you have more than one exit-path for your loop, for instance:
while(true)
{
if(a == 3) break;
if(b == 7) break;
// some more code
}
Of course this code is quite contrived and could easily be replaced by if(a == 3 || b == 7) break but sometimes you can´t (or don´t want to) combine all your conditions into one single. Furthermor this could be usefull if you want to break iteration on some condition but continue on another (to reduce nesting of your code for example).

Categories