Saturday, October 13, 2012

10/13/12 If and else

Today I will teach you about If and else statements and how to code them in Java. Last week, I tough you how to use booleans and evaluate if a statement is true or false. An if statement runs if and only if the boolean that is entered as a parameter is true. If the parameter is false and you have an else statement right after the if statement, then the else statement will run instead of the if one. This is an example of an if statement in Java:

boolean b = true;

if (b){
 System.out.println("true");
}

else{
 System.out.println("false");
}

This code would print the word true. If b was false instead of true, the code would print false instead. Instead of just entering a boolean by the if statement, you actually can enter any statement that can be evaluated as eater true or false like 2<4 or 1==2. This is a very simple way to use if statement, but you can do more than just this! If you want to, you can have else if statements that only run if the code before it was false and did not run. This is how it would work:

int test = 3;

if (test == 1){
 System.out.println("one");
}
else if (test == 2){
 System.out.println("two");
}
else if (test == 3){
 System.out.println("three");
}
else if (test == 4){
 System.out.println("four");
}
else if (test<=0){
 System.out.println("less than or equal to 0");
}
else{
 System.out.println("greater than or equal to 5");
}

This code would print the word four, but if test was one the code would print one, two it would print two, three would print three, if test was less than or equal to zero, it would print less than or equal to zero. Now if test was anything else, it would print greater than or equal to 5. Because there is no if after the last else, if none of the else if statements work, then the else statement will run.

Hopefully, 

if(you read this post){
 System.out.println("you have learned a thing or two about if and else statements");
}
else{
System.out.println("you should read this post so that you can learn more about if and else statements");

=)

No comments:

Post a Comment