Number Switch Statement - c#

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();

Related

C#: After running program and the input is answered with an if statement, how do i get the program to keep asking the question?

I asked a question in the WriteLine form that requires a numbered input, converted it to an int, used that int in an if-else, and I want the question to be re-asked afterward. Any idea?
Example:
Console.WriteLine("What hour is it?: ");
int hour = Convert.ToInt32(Console.ReadLine());
if (hour > 0 && hour < 12)
{
Console.WriteLine("It's morning.");
}
if (hour > 12 && hour < 18)
{
Console.WriteLine("It's evening.");
}
else if (hour > 18 && hour < 24)
{
Console.WriteLine("It's night.");
}
else
{
Console.WriteLine("Invalid Input.");
}
There are three primary ways to loop in C#
while ( someCond is true or false)
for ( int someVar is 0 and it's less than or greater than or equal to some var)
foreach (someObj in someObjects)
Your code is as follows, in pseudocode.
While the user is doing something
Ask a question
Record the answer
Compare it to your possible conditions
Output a response.
Notice a key-word there in your pseudo-code. Make use of that. When learning it's imperative to take the time to understand every little tiny detail and writing it out in plain language will help you to identify those key-words.
Code Snippet
bool someBool = false;
while(!someBool)
{
//Ask A question
//Record an answer.
//Check Condition
if (true)
{
//Do something
someBool = true;
}
else
{
//Do something else.
//Keep `someBool` set to false
}
}
Now it's up to you to implement your code where it goes to make it function exactly how you want it to function, your conditionals, where it breaks, etc.

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.");
}

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

Is there a way to know what passed through a if statement

My problem is, that I need to now, what statements passed through a If statement. The code is as follows.
int[] Array = {value1,value2,value3}
foreach {int Value in Array)
{
if (Value < 4)
{
// Here i need to know what values passed through that were less that 4, like
// which one, value 1, value 2, and/or value 3
}
So is there a solution for a problem? I'm kind of new to programming.
My problem is that i do not need an else statement, i Need to know if value 1 or 2 or 3 passed through. Exactly which ones are less than 4. EDIT: fixed some mistakes, was in a rush, forgot to put the sign the other way. When they are less than 4, i need to now which values passed through. Ill prob repost tho. As i messed up. I really don't care for now which ones are greater, or the else statement, i skipped that part.
Edit2: I also came up with a solution, but i don't if its good. Should i run a loop when i store values in the if statement, making another if statement, to compare if the ones inside the if statement are the same on the outside, and then knowing which values passed through?
I'm not 100% positive if I understand the question but it seems you can use the else statement
if (Value > 4)
{
// Do your stuff for elements greater than 4
}
else
{
// Do your stuff for elements greater lower or equal than 4
}
How about use for instead of foreach, since you got index of array member, you will know which one passed through
int[] array = {value1, value2, value3}
for (int index = 0; index < array.Count(); index++)
{
if (array[index] < 4)
{
// do sth with index
}
}
int Array[] = {value1,value2,value3}
foreach {int Value in Array)
{
if (Value > 4)
{
// Here i need to know what elements passed through that were less that 4
}else if(Value < 4){
//values < 4 will execute this code
}
I'm going to make a few general suggestions that should hopefully be helpful. First of all, your conditional says if (Value > 4) so you will not go into that code block where you suggest figuring out which elements are less than 4. Instead you'd need an else. So here's one way;
int Array[] = {value1,value2,value3}
List<int> lessThanFour = new List<int>();
foreach {int Value in Array)
{
if (Value < 4)
{
lessThanFour.Add(Value);
Console.WriteLine(Value);
}
}
The above code puts each value which is less than four into a list so you can access them later. It also prints them to the console.
Another option would be to use LINQ;
var lessThanFour = Array.Where(x => x < 4);
foreach (int c in lessThanFor)
Console.WriteLine(c);
The above code uses the Where operator to create a new array with all ints in the original that have a value less than for. The statement x => x < 4 is best to think of in an iterative since where x is the current element. It works the same as the foreach loop. When you execute that code it basically says, for each int x in Array, if x is less than four add it to the result. Then I use a foreach below that to print out the results.
Your question is poorly framed I think but it sounds like you are looking for a switch case.
if (x < 4) {
switch (x) {
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
case 3:
Console.WriteLine("Case 3");
break;
default:
Console.WriteLine("Default case");
break;
}
}

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