C# simple IF OR question - c#

Sorry to ask this as I thought I knew the answer, I want to exit the program if userName is greater than 4 characters or userName is not an account called student. However this even if the userName is only 3 characters and is not student I'm still hitting Application.Exit. What am I doing wrong?
if (userName.Length > 4 | userName != "student")
{
Application.Exit();
}
Shame on me :-(

While you should use || instead of |, they will give the same result in this situation. Despite the upvoting of the other answers, changing | to || will not solve your problem.
Your real problem is that the conditions you want to check for will always be true. Either your userName is not student, or it is student and then it is also longer than 4 characters.
When you have a username that is only 3 characters it is not equal to student, therefore the program quits.
From your description of what you expect, I think you mean this:
if (userName.Length > 4 && userName != "student")
{
Application.Exit();
}

You need to use the boolean OR (||) operator instead of the bitwise OR (|)
As I said in my comments though, your logic doesn't necessarily make any sense to me. The way it is writting, the statement will always be true:
If userName is not student, the statement is true and the application exits.
If userName is student, then length > 4 and the statement is true again (which causes an exit).
You could change things to:
if(username.Length > 4 && userName != "student")
{
Application.Exit();
}
Which makes more sense logically, but since I don't know your intent I can't guarantee that it would work the way you want it to.

From looking at your requirement your check for the length of chars is negligable or at least you haven't mentioned the reason why you want to check length of the char. From the example you have provided I would simply check if (userName != "student") I don't see the need for the extra check this is something that can be forced in the UI.

If I am not wrong, you are trying to enter into the if loop when either of the condition is true.
i.e., enter into the if loop
when Length is greater than .
when userName should not be equal to "student"
condition like username = "ABC" is not "student", your condition still right and will enter. It will execute still when userName is equal = "student";
Here You should use AND operator than just OR operator.
if (userName.Length > 4 & userName != "student")
{
Application.Exit();
}
You can also achieve the same result with && operator. & opertor is same as && operator.
when X = false and Y is true; Y will not be evaluated at all. Since X is already false. this is method is also call short-circuit evaluation.

if (userName.Length > 4 || userName.ToLower() != "student")
{
Application.Exit();
}
Try this.

Related

Where and how to use && Operators

I have this piece of code which i simplified from my app. It does what I want but I know its not put in the most efficient way because I'm still having some trouble understanding the && and & operators.
if (AgeInput.Text.Equals(""))
{
Textblock1.Text = "✘";
}
else if (AgeInput.Text.All(Char.IsNumber)){
Textblock1.Text = "✔";
//DO-THIS-A
}
else
{
Textblock1.Text = "✘";
}
I need it to make sure there is no white spaces in the string and to also check so its not empty and finally check if its a number, If it ticks all those requirements it will //DO-THIS-A
Whats the most efficient way to do this?
EDIT:
If somebody knows how to make a XAML textbox numerical only (so no whitespaces) that would be even better (only a single property or don't worry otherwise)
if(!String.IsNullOrEmpty(AgeInput.Text) && AgeInput.Text.All(char.IsNumber))
Textblock1.Text = "✔";
else
Textblock1.Text = "✘";
String.IsNullOrEmpty returns true if the input is as stated: Null or Empty.
We Invert that with the "!", so that it returns true if it isn't empty.
Then we add the && Operator to expand the if condition and ask if the text only contains numbers.
Also look here: For a description of the difference between &, && and |, ||
Not really sure I understand your question, because && and & are for totally different uses.
if (string.IsNullOrWhiteSpace(AgeInput.Text))
{
Textblock1.Text = "✘";
}
else if(Char.IsNumber(AgeInput.Text.All))
{
Textblock1.Text = "✔";
}
The & is a binary operator and && is a logical operator.

What does variable = !variable mean?

I have this code. What does it mean?
bool q = false;
if (i < 0) {
q = !q;
}
I assume !q means true?
UPDATE: The full code is below. When ! is used in the IF statement, is the variable in that situation always false?
bool q = false;
if (i < 0) {
q = !q;
}
if (!q) {
/// do stuff
}
All it means is it's "not q", so it's opposite of whatever q is.
In the case of a boolean like here, the variable q can be either true or false.
when you put a ! in front of something in most languages, it means "opposite"
As example,
1 != 2
means:
1 is opposite of equal to 2
.
This being for a condition, in your case, it would mean
assign the opposite of q to q.
Also, I believe most people on SO (Stack Overflow) will tell you this question does not belong here because you can find it easily on the internet, if you want, there are various books to learn programming. You can search "it ebooks" on the internet and you will probably find many for free .
As the other poster said, it switches the bool property from true to false. In your example, q starts as false. If i is less than 0 then q becomes true. Then comes the if statement, which says "if q is false, then execute the next code block". q only stays false if i is greater than or equal to 0. So no, the code inside your if block will not always execute. It depends on i.

infinite loop even when I switch off capslock

I am trying break; out of frustration. Is there an event handler I need to know about in console?
You're only setting the value of capslock once, prior to entering the loop. bool is a value type, so you get a copy of the Console.CapsLock property, not a reference to it. Your variable is never going to change value after that first assignment. What you want is something like:
while(Console.CapsLock)
{
// inform user, perhaps remove the loop and just tell them once
}
Or
capslock = Console.CapsLock;
while(capslock)
{
Console.WriteLine("CapsLock on");
capslock = Console.CapsLock;
}
On a side note, writing a message as fast as possible in a loop is probably a bad idea since it's just going to fill up the screen before the user has a chance to do anythign about it.
Not to answer your original question but it appears the reason you are checking for caps lock is you want the username that is going to be typed in in all lowercase so you can do a users.Contains(username) or something similar below where you provided in the screenshot.
A better way to do it is use the contains overload that lets you set a comparer, then use a case insensitive string comparer to test.
if(users.contains(username, StringComparer.OrdinalIgnoreCase))
{
//username existed
}
else
{
//username did not exist
}
There are similar overloads for String.Equals that lets you ignore case too
//This would return true if "username = marietjie" and "testUsername = MARIETJIE"
if(username.Equals(testUsername, StringComparison.OrdinalIgnoreCase))
{
//username matched
}
else
{
//username did not match
}
The solution for this kind of problem!!

While or and not equal to not working?

Im quite new to C# and am trying to write a super simple loop
while ((var_app_choice != "Exit") || (var_app_choice != "Test"))
{
//stuff
}
I have a console application where an end user will input a value
If this value is not equal (!=) to Exit OR Test then it should loop.
What am i doing wrong here?
Thanks
If you want to come out of the loop, when the User enters Exit or Test then you need the && operator not ||
while ((var_app_choice != "Exit") && (var_app_choice != "Test"))
{
var_app_choice = Console.ReadLine();
//stuff
}
I think you want and not or...
If the value of var_app_choice is "Test", then the first condition is true and the loop will execute. Similarly, if it's "Exit", then the second condition is true. In other words, you have an infinite loop...
Friend,
Consider I am having a data list as
List dataList = new List() { "Apple", "Microsoft", "exit", "Oracle", "Android" };
int i = 0;
while (dataList[i] != "exit" || dataList[i] != "test")
{
Console.WriteLine(dataList[i]);
i++;
}
You would expect that the ouput should be only Apple and Microsoft. When it encounters "exit" in index 2 it should stop.
What really happens(consider it is verifying "exit") is the first condition fails, which means NotEqualTo Operator works fine. The problem is your OR operator. Since "exit" not equals "test", the condition passed and it further enters into the loop.
Your data must not be equal to "exit" and also not equal to "test".
Think you got the problem. For your information, While(condn){} here you can mention any condition that outputs a boolean(true or false).
Thanks and Correct me if I am wrong.

Help with a C# conditional statement dealing with Strings

In my attempt at dissecting a bit of C# I am afraid I do not understand either the goal or the logic of this bit of code:
if (!string.IsNullOrEmpty(str2) && (Strings.UCase(Strings.Left(str2, 1)) != Strings.Left(str2, 1)))
{
return false;
}
I understand the first part is checking if str2 is "not null", however the second part is coming off a bit flaky. So we UCase the first character of str2, and if it does not equal the first character of str2 (which is NOT "UCase"d), then return "false"?
Maybe I am not missing anything and what I described above is in fact what the code is doing. If this is the case, can we reform this into something else that offers the same result,say for example, check if str2 is uppercase or not? I feel like this is the end goal.
You thoughts?
Yes, you understood the code right.
It looks like something translated from VB using a translation tool, as it's using functions from the VisualBasic namespace. I would rather write it with String methods:
if (!String.IsNullOrEmpty(str2) && str2.Substring(0,1).ToUpper() != str2.SubString(0,1)) {
return false;
}
Or simply getting the first character as a character instead of as a string, and use the IsLower method of the Char class:
if (!string.IsNullOrEmpty(str2) && Char.IsLower(str2[0])) {
return false;
}
My bet is that they are really just testing whether the first character is uppercase. The initial "IsNullOrEmpty" test is just there to make sure that the real test doesn't throw an exception.
The big question: if there is no string value (null or empty) this will not return false. Is that the expected outcome?
Code Objective in English :)
If the non-empty string begins with a lower case character then return false
This is the same, but refactored:
if (!string.IsNullOrEmpty(str2)) {
string s = Strings.Left(str2, 1);
if (Strings.UCase(s) != s) {
return false;
}
}
It is clear that this code tests that the first letter of str2 is or isn't in uppercase when it has any character.
I share the perceptions you have when you say : "I do not understand either the goal or the logic of this bit of code" :) A test that returns only 'false is "fishy" : presumably "something" is waiting for a boolean to be returned, and nothing is returned if the result of this evaluates to 'true.
But if I had to write such a function I'd use the alternative OR logic :
return (! (String.IsNullOrEmpty(testString) || testString.ToUpper()[0] == testString[0]));

Categories

Resources