They are the more common conditional statement. They are more common since most of the time there are only a couple of possibilities, which makes a if-else statement a better fit for the program. A switch statement is normally used when there are several possibilities that may or may not branch off.
A if statement is formatted:
if(condition)
{
}
Else if(condition)
{
}
Else
{
}
The only necessary part of a if statement is the if(condition) because else if is only used if there are 3 or more possibilities and else is only used if you need to do something if the condition on the if isn’t true. Also the braces are only necessary if there is more than one line for the statement( if, else if, or else).
The condition is a comparison of some sort using either some sort of equals or campareTo method or comparison operators, and they can include logical operators in case either two or more things need to be true or the outcome is the same for multiple possibilities. For example say for a dice game if you role a 3 or a 7 you win. It doesn’t make sense to use if and else if since both of those possibilities will have the same outcome, so you only you the if and just make the condition (k=7 || k=3).
Also break statements can also be used in if statements , be careful with how you use the however because a break statement breaks out of the first set of braces and only the first set of braces so depending on whether or not the if statement has braces it could break out of the if statement or say a statement containing that if statement.
So a example for the break statements is:
if(condition)// this is the if statement that the break will get out of
{
. . .
if(condition)
Break;
. . .
}
if(condition)
{
. . .
if(condition)// this is the if statement that the break will get out of
}
Break;
}
. . .
}
A good example of if statement being used is in the fc converter public method step-by-step video.
One thought on “If Statements”
Comments are closed.