|
Home <<Table of Contents <<Arrays Loops>> |
To be useful, a program must be able to react to changes. The concepts presented here allow you to do just that. They are essential to any serious programming language. If you are familiar with C/C++ or similar languages, this will all seem very fimiliar. | |||||||||||||||||
|
The If Statement
Allow me to go into greater depth about the structure of an "if statement." First, comes the word "if" (I hope you have figured that out by now), then inside the parenthesis is the condition. If the condition is true, all code inside the braces is executed, if it is not, the code inside the braces is ignored. Now, if this person's grade is exactly sixty-six, you might want to tell him that he just barely passed (surprisingly).
Notice there are two equal signs, that is not a typo (you thought you had me there). This is one of the most common mistakes for people who are switching from "BASIC" to Java or C/C++. If you only use one equal sign, your program will not work. There are several operators you may use in your conditions.
I hope you found my table informative. Basic programmers should find all of these operators familiar except one. In the interest of saving BASIC programmers much frustration, you always use the "!=" operator if you want to check for a value being unequal to another value. You do not use a greater-than and less-than sign next to each other.
You may also use parenthesis inside of the condition.
| ||||||||||||||||||
|
The Else and Else if Statements
Else statements are simple enough. If the condition provided in the "if statement" is true, the following code is executed but not the code in the "else statement." If the code is false, the "if statement's" code is ignored and the "else statements" code is executed.
Very simply, the computer checks each condition, if none of the conditions are true, the code in the "else statement" is executed. If more then one of the conditions are true, both of them will be executed, and if you modify a variable that makes a following condition true (e.g. you change the value of "grade" inside one of the "else if statements"), the statement will execute. | ||||||||||||||||||
|
Switch Statements
In a "switch statement," you must put a variable of type char, byte, short, or int (see "Variables in Java") in the parenthesis. Every "case block" checks for a certain value of the variable; if it matches, the code is executed. If there are no matches, the default case block is executed. In Java and C/C++, code in the case blocks "falls through;" when a "case block" matches, the code in all of the following "case blocks" is executed along with the one that mathces. To stop this from happenning, you must put a "break;" statement at the end of all your "case blocks." The "break" statement exits the the "switch statement." It is not needed for the last "case block" because there is no code after it in the "switch statement." |
Home <<Table of Contents <<Arrays Loops>> |
|