Else does not work - c#

I am not sure what I am doing wrong! The else command and the bracket above it seem not to act correctly:
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (username_txtb.Text == username && password_txtb.Text == password);
{
MessageBox.Show("You are now logged in!");
}
else ;
{
MessageBox.Show("Sorry, you have used the wrong username and password. Please try again.");
}
}

Note that:
else ;
is equivalent to:
else
{
}
So:
else ;
{
//some code
}
is equivalent to:
else
{
}
{
//some code
}
And more clearly, it's equivalent to:
else
{
}
// the conditional clauses are over,
// nothing special here except for an extra scope
// which is a valid construct (even though being useless here)
{
//some code
}
The second block is not really related to the condition - it just a code block in brackets creating a useless scope, and will be always executed.
The same rules apply after if.

else ;
should be
else
Remove the semicolon, it will prevent the body from executing.
private void button1_Click(object sender, EventArgs e)
{
if (username_txtb.Text == username && password_txtb.Text == password) //; - remove
{
MessageBox.Show("You are now logged in!");
}
else //; - remove
{
MessageBox.Show("Sorry, you have used the wrong username and password. Please try again.");
}
}

The presented code results in a syntax error that should read:
Invalid expression term 'else'
The syntax error is caused by the semicolon trailing the if (the semicolon after the else will result in "unexpected behavior" when running the program, and the same principle applies).
if (..);
{
..
}
else ..
Is equivalent to
if (..)
/* empty statement - no code run when if is true! */ ;
/* arbitrary code in a block *not associated* with the `if` */
{
..
}
else ..
In this case the "arbitrary code block" ends the if-statement grammar construct.
To fix the syntax error (and the semantic problem), remove the semi-colons after both the if and else statements:
if (..) /* no semicolon */
{
MessageBox.Show("..");
}
else /* no semicolon */
{
MessageBox.Show("..");
}

Related

Question about else statement following if-else

I'm brushing up on some C# and had a question that seemed dumb. In C# (and probably most languages), can you put an else statement inside an if-else statement?
e.g.
if (clause) {
execute code
}
else if (clause) {
execute code
else {
execute code
}
}
This should be erroneous.
You probably want something like this instead:
if (clause)
{
// do something
}
else
{
if (anotherClause)
{
// do something
}
else
{
// do something
}
}
I assume you are new to programming, so I can talk a little bit about if else statements.
else does not make any sense when you don't have an if before it.
For example,
This statement makes sense:
IF you are 21 or older, you can drink. ELSE, you cannot drink.
While this does not:
ELSE, you cannot drink
Hopefully my answer helps
it is not possible but you can do something like that instead :
if(condition)
{
//code that get executed after cheking the condition
}
else if(another condition)
{
// code that get executed after checking the second condition
}
else
{
// code get executed if the first and the second condition are not true
}
That code wouldn't work because you need an if for there to be an else. If you want to do an additional check for something within the else if, you need to add an if first, like this:
if (clause)
{
execute code
}
else if (clause)
{
execute code
if (clause)
{
execute code
}
else
{
execute code
}
}

How to stop execution of if-statement

Hi I want to stop the execution of if-loop ,I have tried with 'return' statement but its exits from the function ,So how can I exit from the single if Statement.I have tried with following code...
Here I want to stop execution of if(CheckHorizontalSide(SourceMember)) and by stopping this I want to move towards the if(CheckTop(SourceMember))
void A()
{
if (CheckHorizontalSide(SourceMember))
{
if (lblHorizontalMember.Text == DestinationMember)
{
lsRelationPath.Add(lblHorizontalMember.Text);
lblRelationPath.Text = String.Join("-", lsRelationPath);
lblRelationPath.Visible = true;
return;
}
bool WhetherContains = lsRelationPath.Contains(SourceMember);
if (WhetherContains)
{
return;
}
//This below code is not related to the above 'WhetherContains '
lsMemberID1.Clear();
lsRelationPath.Add(lblHorizontalMember.Text);
Find_Route(lblHorizontalMember.Text, DestinationMember);
}
if(CheckTop(SourceMember))
{
//code here....
}
}
You put the rest of the block in a sub-block with { } and put else in front of that.
You can nest as deeply as you want but you might try factoring out blocks to helper functions to reduce the complexity and give statements a name.
if (WhetherContains)
{
// this is actually empty
}
else
{
lsMemberID1.Clear();
lsRelationPath.Add(lblHorizontalMember.Text);
}
Or,
if (!WhetherContains)
{
lsMemberID1.Clear();
lsRelationPath.Add(lblHorizontalMember.Text);
}

unable to show the last item in the stack pop ()

I'm implementing backword function on a button. that when clicked moves to the previous link in the stack. the problem is this if it has one element in the stack pop() it gives an error of stack empty.
private void Backward_Click(object sender, EventArgs e)
{
try
{
if (simpleStack.Count != 0)
{
simpleStack.Pop();
string open = simpleStack.Pop();
PopulateListView(open);
complicatedStack.Push(open);
}
else if (simpleStack.Count == 0)
{
Backward.Enabled = false;
}
It works when I have more than one clicks n goes back to the previous item selected.but does not show the last one. I'm passing string in simpleStack. can anybody tell me what I'm missing?
Look at your code:
simpleStack.Pop();
string open = simpleStack.Pop();
You're popping twice, and ignoring the first result. Why would you do that? I suspect you can just remove the first Pop call.
Also note that your else clause doesn't need to check simpleStack.Count == 0 - it must be, otherwise you wouldn't be evaluating the else clause. (Unless you've got multiple threads doing stuff of course - which wouldn't be a good idea.)
Try this -
private void Backward_Click(object sender, EventArgs e)
{
try
{
if (simpleStack.Count != 0)
{
//simpleStack.Pop(); // Remove this line
string open = simpleStack.Pop();
PopulateListView(open);
complicatedStack.Push(open);
}
else if (simpleStack.Count == 0)
{
Backward.Enabled = false;
}
}
}

Validation in method continues to run the rest of code even though "return" is specified

My code doesn't terminate on a true condition if called from another method. For example,
void RunValidation()
{
if (NameEntered == string.Empty)
{
MessageBox.Show("No name has been entered");
return;
}
}
void CreateUser()
{
RunValidation();
//Run more code
}
If I call the validation method inside the create user method, the messagebox shows up but the rest of the code gets executed even though "return" was specified.
If the validation code is not inside a method and called directly in the CreateUser method, the rest of the code doesn't run (which is what I want). I want to be able to call a validation method inside many other methods and if the conditions are true, to stop executing other code in the methods.
What is the correct way of doing this? Do I have to use some sort of try and catch?
You are returning from the RunValidation method, not the CreateUser method. If you want to control the flow of the CreateUser method based on the results of RunValidation, do something like this:
bool Validate()
{
if (NameEntered.Equals(string.Empty))
{
MessageBox.Show("No name has been entered");
return false;
}
return true;
}
void CreateUser()
{
if (Validate())
{
// Run more code
}
}
The return statement only affects the current method. Read more about the return statement here.
return; exits the RunValidation() method.
It has no effect on the function that called it.
Instead, you should make RunValidation() return a boolean indicating whether the validation succeeded.
In the calling method, you can check if it returns false and return; from there too.
you can do something like:
bool RunValidation()
{
if (NameEntered == string.Empty)
{
MessageBox.Show("No name has been entered");
return false;
}
return true;
}
void CreateUser()
{
if(RunValidation())
{
//Run more code
}
}
U talking about this code block?
void RunValidation()
{
if (NameEntered == string.Empty)
{
MessageBox.Show("No name has been entered");
return;
}
}
because if you are, I don't know what "rest of code" it's executing, because there is no code after the return statement.
If you're talking about this
void CreateUser()
{
RunValidation();
//Run more code
}
then yes, just because RunValidation had a return statement doesn't mean that it's calling method will return. that kind of behavior would cause crazy bugs.
Now, in order to achieve yoru expected behavior, you can change runValidation to
bool RunValidation()
{
if (NameEntered == string.Empty)
{
MessageBox.Show("No name has been entered");
return false;
}
return true;
}
and then call it like
void CreateUser()
{
if(RunValidation())
{
//Run more code
}
}

Do loops and while loops

When I type in the word "Andrea" the program crashes. I am guessing, but I think it's because I am inside the loop and it doesn't know when to stop. If I am correct can you tell me how to get out of the loop. when I put a break in it tells me there is no loop to end.
private void button1_Click(object sender, EventArgs e)
{
do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
while (textBox1.Text == "Andrea");
break;
do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
while (textBox1.Text == "Brittany");
do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
while (textBox1.Text == "Eric");
break;
MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
You have textBox1.Text == "Andrea" and textBox1.Text == "Brittany" as your loop conditions, but you don't seem to be changing that value anywhere in the code. Therefore, you have an infinite loop which will result in your program crashing.
I'm not certain what your program is meant to be doing, but your options to break out of a loop are:
Use a break; statement to exit the loop.
Change your loop condition to something which can eventually result in false.
Change the textBox.Text property somewhere in the loop body.
Alternatively, you could use an if statement to check the condition once, and execute some code if that condition is true.
Edit:
I have done this with if statements but now i am looking to try doing the same thing with loops
no purpose just trying to learn how to program
In response to the above comments, I'll tell you how to replace an if statement with a loop. Just do it like so:
// Check the condition before executing the code.
while (textBox1.Text == "Andrea") {
// Execute the conditional code.
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
// We actually only want to execute this code once like an if statement,
// not while the condition is true, so break out of the loop.
break;
}
In your original post, you are using a do while loop rather than a while loop. You should keep in mind that the do while executes once for certain, regardless of whether its condition is true. It only checks the condition to see whether it should run additional times. The while loop, on the other hand, checks the condition before executing at all, which means you can substitute an if statement with it.
You should keep in mind that this is a bad practice. If you want to execute code depending on a certain condition, use an if statement. If you want to execute code repeatedly a certain number of times or while some condition is true, then use a loop.
At a glance, it looks like you have an infinite loop. As soon as you type in "Andrea" in textBox1 and click button1, it will perpetually update Commission.Text, not interrupting the thread to process any additional input.
The bigger question is, what the heck is this program supposed to be doing? And why is it doing it in a loop?
I suspect that by while you actually mean if. Otherwise, do you get an error message or exception when the application crashes? Can you wrap this function in a try/catch to see what the exception is?
Edit To clarify, try this method body:
private void button1_Click(object sender, EventArgs e)
{
try
{
if(textBox1.Text == "Andrea")
{
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
}
else if(textBox1.Text == "Brittany")
{
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
}
else
{
MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(), "Bad Spelling");
}
}
}
}
Adding to what FacticiusVir said earlier, you can also do this in a switch statement (and since we're calculating the same commissions for each person, they can be combined:
private void button1_Click(object sender, EventArgs e)
{
switch(textBox1.Text)
{
case "Andrea":
case "Brittany":
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
break;
default:
MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
}
}
If you want to do different commissions per person you need to split it (in the below Brittany is getting a different commission value now):
private void button1_Click(object sender, EventArgs e)
{
switch(textBox1.Text)
{
case "Andrea":
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
break;
case "Brittany":
Commission.Text = (Convert.ToDouble(textBox2.Text) / 15).ToString();
break;
default:
MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
}
}
The do { x } while (y) construct runs x once, and then proceeds to run x continuously as long as y is true.
You're not having any success because you seem to be structuring it like this:
do
{
// This will just run over and over...
}
while (condition); // ...because this is always true.
break; // This isn't even in the loop!
In other words, the point where you're trying to add your break (based on a comment you left on another answer) is outside the loop, which is why your code is running indefinitely.
Now, it sounds like you're really just trying to use a do/while to emulate an if statement, presumably as a challenge to yourself. If that is the case, do yourself a favor and give up on that idea.
You cannot use a do/while loop to emulate an if condition, because do will always run at least once. The only way you could ensure that it runs exactly once under a specific condition (i.e., what if does) would be by embedding an if statement inside the do loop, which would defeat the purpose of the exercise.
That said, you can emulate an if with a while:
while (condition)
{
// Execute code once.
break; // Then just quit.
}
Looking at this one piece:
do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
while (textBox1.Text == "Andrea");
...what do you expect to happen if textBox1.Text == "Andrea"?
What the program is doing is checking your comparison test, then if it's true, it does what is inside of the do / while block, then it checks the comparison test, then if it's true, it does what is inside of the do / while block, then it checks the comparison test, then if it's true, it does what is inside of the do / while block, then...
Get the point?
You use do / while loops if the condition is going to change inside the loop (or you explicitly break out of it).
What you want instead is to change it to something like
if( textBox1.Text == "Andrea" )
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
Just a guess, but as FacticiusVir says, you probably want to use conditionals instead of loops:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "Andrea" || textBox1.Text == "Brittany")
{
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
}
else
{
MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
}
}

Categories