c# != operator not functioning correctly - c#

I don't know if it is just me being thick but I have a bit of validation code to check for a yes or no answer.
I can't seem to get it to work I have used the code in other places in my program and it works but I can't spot the error if there is one. The code runs through the while anyway no mater what the input character is.
string correctDestenation = Console.ReadLine().ToLower();
while (correctDestenation != "y" || correctDestenation != "n")
{
Console.WriteLine(
"Oops! You must enter a 'y' for yes and a 'n' for no");
correctDestenation = Console.ReadLine().ToLower();
}

Your logic is incorrect. You want to use && instead of ||.
while (correctDestenation != "y" && correctDestenation != "n")
or, you can use De Morgan's Law and look at it the other way, which is equivalent:
while (!(correctDestenation == "y" || correctDestenation == "n"))

That condition will always be satisfied, as a character will not be equal to 'y' or equal to 'n'. Use && instead of ||.

How about you use the AND operator
while (correctDestenation != "y" && correctDestenation != "n")
{
Console.WriteLine("Oops! You must enter a 'y' for yes and a 'n' for no");
correctDestenation = Console.ReadLine().ToLower();
}

Related

Multiple conditions in c#

while (playerMove != "SCISSORS" || playerMove != "PAPER" && playerMove != "ROCK" || string.IsNullOrEmpty(playerMove))
{
Console.WriteLine("Please enter a valid command!");
playerChoice = Console.ReadLine().ToUpper().Trim();
continue;
}
Can someone explain to a beginner programmer why this code doesn't work.
The way I read this code myself is:
While playerMove isn't "SCISSORS" or "PAPER" and isn't "ROCK" or Empty, do this...
How do I make this work?
If you enter "PAPER", then playerMove != "SCISSORS" is true, so your while-condition is true, because only one part of a logical OR has to be true.
You want all of the !="XYZ" to be true, OR the string to be empty:
while((playerMove != "SCISSORS" && playerMove != "PAPER" && playerMove != "ROCK") || string.IsNullOrEmpty(playerMove))
That said, there are probably easier ways to check this.
You could define a list of acceptable strings, for instance, and check against that:
using System.Linq;
...
var acceptedString = new List<string> {"ROCK", "PAPER", "SCISSORS"};
...
while (!acceptedStrings.Contains(playermove)
{
// error message
}
Actually checking for an empty string is useless, since an empty string never has an accepted value.
Another option, as mentioned in a comment, is to extract your condition to a method. This is almost always a good idea for complicated conditions:
while (!IsValid(playermove)){...}
...
private static bool IsValid(string move)
{
return move == "ROCK"
|| move == "PAPER"
|| move == "SCISSORS";
}
Alternatively you can rewrite that to
while (!IsValid(playermove)){...}
...
private static bool IsValid(string move) =>
move == "ROCK" || move == "PAPER" || move == "SCISSORS";
I feel so dumb right now, i only just noticed i broke my head over this code for no reason.
I noticed in the loop i asked to set a new value to "playerChoice", instead of playerMove. hence why it didnt run the way i wanted it to.
while ((playerMove != "SCISSORS" && playerMove != "PAPER" && playerMove != "ROCK") || string.IsNullOrEmpty(playerMove))
{
Console.WriteLine("Please enter a valid command!");
playerMove = Console.ReadLine().ToUpper().Trim();
continue;
}
Including answer into the conditions aswell.

Trying to make quit sequence that only proceeds when correct input is given

i'm having trouble creating a loop that will request user input and if the input is not "Y" or "N" to re-prompt the user to input over and over until they give the correct input.
while (quitOrContinue != "Y"|"N")//cant use "Y"/"N" in the same line, how do I phrase this line?
Console.Write("\nWould you like to process another set of bowling scores?");
Console.WriteLine("\nPress 'Y' to process another set or 'N' to exit the program");
Console.Clear();// this needs to happen if the input to run again is "Y"
Well, for starters, you're not actually taking any input at all from the user. You can use Console.WriteLine to output whatever sort of instructions you want from the user, but you have to actually capture them somehow.
To get input, you'd have to use Console.Read(), and you'd have to use conditional blocks to check their input. You should wrap your code in a while loop that references a sentinel value:
bool userIsDone = false;
Console.Write("\nWould you like to process...");
while (!userIsDone)
{
string userInput = Console.ReadLine();
// ...
if (userInput == "Y")
{
// process another set here
Console.WriteLine("\nWould you like to process...");
}
else if (userInput == "N")
{
// exit your program
}
else
{
Console.WriteLine("That input is invalid.");
}
}
Also, about the code you have above - you should wrap the elements inside loops in { }, and the | is the bitwise OR, not logical or. Logical or (which I'm 99% you want in this situation) is ||, and logical and is &&.
Why not use a loop ?
string input = null;
while((input = Console.ReadLine()) != "Y" || input != "N")
{
Console.WriteLine("Invalid value, please try again:");
}
Here the expression (input = Console.ReadLine()) != "Y" || input != "N" will be evaluated before and each time after the loop runs. It basically reads a line from the input stream and assign it to input variable then checks if it's not Y or N it executes the loop body and evaluates the expression again and ask for input until the condition satisfies.You can use Console.Read method to read one charachter but it returns int so you need to cast it to char.

How to use multiple conditional operators using C#

I want to use combination of the 2 operators: the && and the || operator using C#. I have 5 variables that I would like to make sure if these conditions are met.
varRequestedDate
varTotdayDate
varExpectedDate
Approval1
Approval2
Here is what I have for my current condition but would like to add other variables adding the OR operator:
if (varRequestedDate != (" ") && varExpectedDate < varTotdayDate)
here is the pseudocode for what I would like to see after the updated version:
(if varRequestedDate is not blank
and varExpectedDate is less than varTotdayDate
and either Approved1 OR Approved2 = Yes)
send email()
i cannot figure out how to do this.
thanks
You just have to add nested parentheses:
if (varRequestedDate != " "
&& varExpectedDate < varTotdayDate
&& (Approved1 == "Yes" || Approved2 == "Yes")
)
sendEmail();
For the sake of readability and expressiveness I would extract the boolean values into meaningfully named variables:
var isDateRequested = varRequestedDate != (" ");
var isDateWithinRange = varExpectedDate < varTotdayDate;
var isApproved = Approved1 == "Yes" || Approved2 == "Yes";
if (isDateRequested && isDateWithinRange && isApproved)
{...}
You can nest logical operators using parentheses (just like arithmetic operators). Otherwise they follow a defined precedence going left to right.
if (
varRequestedDate !=(" ") &&
varExpectedDate < varTodayDate &&
(Approved1==Yes||Approved2==yes))

If statement clarification of AND/OR

I'm sorry to ask such an easy question.. I just need some clarifications, because sometimes I mix the differences up.
Can somebody please help me by explaining the difference between the following if statements?
sending = true;
if (sending && e.AssetType == AssetType.Notecard) //#1
vs.
if ((sending) && (e.AssetType == AssetType.Notecard)) //#2
vs.
if (sending || e.AssetType == AssetType.Notecard) //#3
vs.
if ((sending) || (e.AssetType == AssetType.Notecard)) //#4
In this specific case, I need it to evaluate to something like:
"If(sending == true AND e.AssetType == AssetType.Notecard)"
In an other case I need the if statement to check one string and contents of a list like:
"If(string == "Name" OR List.Contains("string"))
The first and the second statements are the same (parenthesis are not obligatory in this case, because of C# evaluation priorities!)
if (sending && e.AssetType == AssetType.Notecard)
if ((sending) && (e.AssetType == AssetType.Notecard))
just as:
if ((sending == true) && e.AssetType == AssetType.Notecard))
if ((sending) && (e.AssetType == AssetType.Notecard))
Also the 3° and the 4° statement will give the same result, for the same reason mentioned above: http://msdn.microsoft.com/en-us/library/6a71f45d.aspx
I would use these statements:
if (sending && (e.AssetType == AssetType.Notecard))
and:
if ((string == "Name") || List.Contains("string"))
(but please take care of string comparison modes, such as upper/lower cases and cultures:
String.Compare(string, "Name", StringComparison.CurrentCultureIgnoreCase) == 0
compares strings without regard of the case and with the current culture)
There is no any difference in those codes.
if ((sending) && (e.AssetType == AssetType.Notecard)) and if (sending && e.AssetType == AssetType.Notecard) evaluates into the same thing.
if(sending == true) or if(sending) is the same thing too.
If you're asking about difference between || and &&:
|| is a LOGICAL-OR. It's enough that only one condition would be TRUE to pass if
&& is a LOGICAL-AND. All conditions must be TRUE in order to pass if
In both cases the evaluation will be done from the left to right.
Example of sequence:
if ((sending) && (e.AssetType == AssetType.Notecard)) => if sending==true AND ..rest..
For the first and second statements produce the same result and for the third and fourth statements also produce the same result.
A couple of things to clarify:
In this case, parentheses are not required and it is just extra code.
When you use Logical-AND operation, the first part is always evaluated, and the second part will only be evaluated if the first part is true.
When you use Logical-OR operation, both parts are always evaluated.
When you have more than +2 expressions, then use parentheses to clarify your intentions. e.g. if(A && B || C) is the same as if((A && B) || C) because the Operators Precedence. but if you want the logical-OR operation to be execute first, then you must use parentheses to override the precedence if(A && (B || C))
Furthermore, if(A && B == C) is the same as if(A && (B == C)) because Equality operation has higher precedence than logical-AND

If statements always passing to else statement

I'm working on a simple password storage console application in c#.
I'm having a bit of a problem on a section that asks if the user would like to mask all password entries from that point on.
This is the section of code:
bool tryagain = true;
while(tryagain == true)
{
Console.WriteLine("Would you like to mask all other password entiries?(Y,N)");
string input = Console.ReadLine();
if (input == "y" | input == "Y")
//Something wrong, always passes to Your awnser was invalid
{
maskpass = true;
tryagain = false;
}
if (input == "n" | input == "N")
{
maskpass = false;
tryagain = false;
}
else
{
Console.WriteLine("Your awnser was invalid, would you like to try again?");
string yesno = Console.ReadLine();
if (yesno == "y" | yesno == "Y")
{
tryagain = true;
}
if (yesno == "n" | yesno == "N")
{
Environment.Exit(0);
}
}
}
The problem is when I run the code it always runs to the else statement.
I'm certain the mistake is very simple and I'm just being ignorant but anyone have any idea on whats going on here?
Use || instead of single |. The || mean or conditional, but single | is binary or.
I assume that the logic of your code says:
if input=='y' OR input=="Y", do something.
Another suggession yet. If my assumption right, you can achiev that with simple String.Equals overload:
if(input.Equals("y", StringComparison.InvariantCultureIgnoreCase)
{
//do something/
}
You can either use || or you can use the method of the String class String.equals. Since it is a String you are reading as input better use the String.equals method

Categories

Resources