I want to create a simple do-while statement that makes sure the user input is either Y or N and if not asks them to input again. If it is Y or N then the app continues. This is what I have so far but my application though it is just stuck in a loop asking the user input. New to C# -- thanks for any help.
string answer = "";
do
{
//Ask the user if they want to roll the dice
Console.WriteLine("Would you like to roll the dice (y or n)?");
//Get the user's response and validate that it is either 'y' or 'n'.
answer = Console.ReadLine();
} while (answer != "Y" || answer != "N");
Looks like a simple boolean logic error.
Your while statement should be:
while (answer != "Y" && answer != "N");
Since you want to be sure that the answer is not yet Y and the answer is also not yet N. Loop while it is neither. Hope this helps!
Your logic is OR || instead of AND &&. It will always either not be Y or not be N because it cannot be BOTH at once. When it's N it isn't Y and the opposite is also true.
Use AND && instead.
Also, your comparison is case sensitive. Consider checking for upper and lower case.
2 things
As all said replace || with &&
Match uppercase of what user enter with your Y & N cause user can enter y. A Y and y, both are positive decisions of user.
answer.ToUpper() != "Y" && answer.ToUpper() != "N"
Change the || to an && and this should fix it for you.
Another way to look at it could be this:
The break conditions is whenever the answer is "Y" or the answer is "N".
You want the loop to continue whenever the break condition is not met so you can have
(answer == "Y" || answer == "N") and then not the result
while(!(answer == "Y" || answer == "N")
Related
I'm making a simple calculator app and I've been racking my head on this one because I'm trying to loop the question whenever the user inputs the wrong choices.
Console.WriteLine("\nChoose an operation:");
Console.WriteLine(" ------------------ ");
Console.WriteLine(" | Addition: + |");
Console.WriteLine(" | Subtraction: - |");
Console.WriteLine(" | Multiplication: x |");
Console.WriteLine(" | Division: / |");
Console.WriteLine(" ------------------ \n");
operators = Console.ReadLine();
while (operators != "+" || operators != "+" || operators != "+" || operators != "+")
{
Console.WriteLine("Please input correct operation: ");
operators = Console.ReadLine();
}
It would perhaps be simpler to understand if you replace your logic:
operator = Console.ReadLine();
var acceptableOperators = "+ - x /".Split();
while (!acceptableOperators.Contains(operator))
{
Console.WriteLine("Please input one of: " + string.Join(" or ", acceptableOperators);
operator = Console.ReadLine();
}
The crucial part is the logic becomes
"While not this list of acceptable operators contains the user input" or in other words, "while what the user inputted is not present in the list of acceptable operators"
This is easy to extend just by adding more operators to the string and the error message changes automatically. It supports multi char operators too
Note you shouldn't use a variable named as a plural if it isn't a collection or array (call your variable operator)
Your original logic was wrong for two reasons:
One that you made a copy paste error that repeated "+" four times
Two when humans say "check that this light is not blue or red" they mean !(light == blue || light == red) - the brackets are important. You could also say "check this light is not blue and is not red" to mean the same thing - in C# it's light != blue && light != red, but you cannot say "light is not blue OR light is not red" because it's always true no matter what color the light is.
Because (English speaking at least) humans tend to say the first form ("check the light isn't blue or red") without any obvious bracketing in the speech, it tends to guide newbies psychologically towards wanting to write light != blue || red then they remember that c# has to repeat the variable for each check so it becomes light != blue || light != red when it should have been !(light == blue || light == red)
it should be && instead of ||, so user can only input + or - or x or /
while (operators != "+" && operators != "-" && operators != "x" && operators != "/")
{
Console.WriteLine("Please input correct operation: ");
operators = Console.ReadLine();
}
Your code logic can be simplified and made more user friendly (not need to ask for an 'Enter' every time an operator is chosen):
char key;
while (true)
{
key = Console.ReadKey().KeyChar;
if ("+-x/".Contains(key)) break;
Console.WriteLine("\nPlease input correct operation: ");
}
Console.WriteLine($"You pressed {key}");
This might just be me, but I've been trying to do a do...while loop in c# where the loop will end if either one of two conditions are true.
I'm using the || operator. Google tells me that that is OR, but my loop is only ending when both conditions are true. What am I doing wrong?
Here is a code example:
int sugar=0, salt=0, value=0;
string tLine;
Console.WriteLine("Enter integer values to add to Sugar and Salt.");
Console.WriteLine("The loop should end when either one reaches 10 or more.");
do {
Console.Write("Sugar? =");
tLine = Console.ReadLine();
int.TryParse(tLine, out value);
sugar =sugar+value;
Console.Write("Salt? =");
tLine = Console.ReadLine();
int.TryParse(tLine, out value);
salt =salt+value;
}while ((sugar<10) || (salt<10));
Console.WriteLine("Sugar={0}, Salt={1}", sugar, salt);
Console.ReadKey();
Since the condition in English is:
"The loop should end when either one reaches 10 or more."
Then the condition should be:
do
{
...
}
while (Sugar < 10 && Salt < 10);
You need to use '&&'. Then if either Salt or Sugar becomes >= 10, the result of the && will be false and the loop will therefore terminate.
However, you can use || by inverting the result of the comparison, like so:
while (!(Sugar >= 10 || Salt >= 10))
But that's much harder to read.
Some languages have until, but C# doesn't. If it did, it would look like:
until (Sugar >= 10 || Salt >= 10)
In other words, until (condition) is really the same as while (!condition).
The loop is executed every time the condition is met. So you have to change it to:
while ((sugar<10) && (salt<10))
or
while (!((sugar>=10) || (salt>=10)));
Or you write
while ((sugar<10) && (salt<10));
As long as both are below 10 the while goes on.
In C#, if I want to check to make sure that a value does not equal X or Y, I would write something like this:
if(x != 1 && x != 2)
{
//dosomething
}
I want to see if there is a way to write that with OR instead of AND. Something like this (which doesn't work, but its what I am trying to do):
if(x != (1 || 2))
{
//dosomething
}
Obviously that doesn't work because it is trying to evaluate 1 || 2 as its own statement. Does there exist a way to write that correctly?
You can always invert an AND into an OR:
if (!(x == 1 || x == 2))
{
...
}
You have to reverse all the conditions to do it though, as above. The process for doing so is described in De Morgan's Laws (thanks #RichardEverett!).
You could try this one:
if(!(x == 1 || x == 2))
but honestly, I don't see the reason of doing so.
This statement if(x != 1 && x != 2) is far more clear and readable than the above and it does the same.
This (x == 1 || x == 2) evaluates to true if x is either 1 or 2. Hence taking the negation of this, you get that you want.
No, C# doesn't support such a construct presently.
The following is about as close as I could get it, but it's slow!
if (!new[] { 1, 2 }.Contains(x)) { ... }
I am currently trying to get my snake console game running but I have came up with something that I do not quite understand. I don't really think that the != operator is not working correctly, so I must have made a mistake but I have no idea why it it is like that:
// not working
if (food.x != snakeElements.Last().x && food.y != snakeElements.Last().y)
// working
if (!(food.x == snakeElements.Last().x && food.y == snakeElements.Last().y))
Isn't it all the same?
Using De Morgan's laws (!a && !b) is the same as !(a || b) so your first example should be:
if (food.x != snakeElements.Last().x || food.y != snakeElements.Last().y)
The && should be || in the first if.
if (food.x != snakeElements.Last().x || food.y != snakeElements.Last().y)
If you write out what you actually mean by your boolean condition, you can see more clearly what the difference is.
// not working
if (food.x != snakeElements.Last().x && food.y != snakeElements.Last().y)
This means:
"The food is not in the same column as the last snake element, and the food is not in the same row as the last snake element"
The logic error is a bit more obvious now. What if the food's position is (10,3), and the last element's position is (14,3)?
Compare with:
// working
if (!(food.x == snakeElements.Last().x && food.y == snakeElements.Last().y))
Which means:
"It's not true that (the food is in the same row as the last snake element and the food is in the same column as the last snake element)"
Now the condition is false if and only if the food has the same X and Y as the last snake element.
No, it is not same.
If this works...
if (!(food.x == snakeElements.Last().x && food.y == snakeElements.Last().y)) // working
Then this should work too...
if (food.x != snakeElements.Last().x || food.y != snakeElements.Last().y) // should work
Notice the change in the sign from logical AND (&&) to logical OR (||).
I think the boolean logic is different in two cases:
both comparisons must be not equal for the if to evaluate to true.
either one has to be not equal for if to evaluate to true
They are different.
To be clear, I'll call food.x as X and snakeElements.Last().x as X', others as Y and Y'.
First one is saying:
if X is different than X' AND Y is different than Y' is true
Second one is saying:
if X is equal to X' AND Y is equal to Y' is false
Assume that X, X', Y, Y' are integers
If we say that X = 3, X' = 5, Y = 1, Y' = 4, first statement is true, because X != X' Y != Y' are both true. However, second would also be true becase X is not equal to X'.
i am trying to check condition before entering into it but it is entering in wrong condition
my conditions are ,
if (Target.Tables[0].Rows[0]["T_B_CX"].ToString() == "0" && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) >= 100000)
if (Target.Tables[0].Rows[0]["T_B_CX"].ToString() != "0" && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) > 10000000)
the values are,
T_B_CX = 0 and T_B_C = 2500000000
it must enter the fist condition i mentioned but it is entering in second condition???
Hopes for your suggestion thanks in advance
you can convert to int and do the comparison as below
if (Convert.ToInt(Target.Tables[0].Rows[0]["T_B_CX"].ToString()) == 0 && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) >= 100000)
may be when we get ToString of cell value it returns not exactly string equal to "0", debug and see which value you get for Target.Tables[0].Rows[0]["T_B_CX"].ToString()
There is no code between the two conditions, so the first one is taken as expected, then the second one is evaluated till the != 0.
Try to write something like this
// Convert everything just one time here
int tbcx = Convert.ToInt32(Target.Tables[0].Rows[0]["T_B_CX"]);
long tbc = Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]);
if(tbcx == 0 && tbc >= 100000)
// code here
else if(tbcx != 0 && tbc > 2500000000)
// code here
Also try to avoid the conversion of an integer value to a string and then check against a string.
It makes no sense. If an integer is stored in that table then convert it to an integer and check against an integer.