If (expression) - Else If (expression) Code Segments
Introduction.
We are about to take another step in our capabilities to handle complex
decisions. In many instances there are many different options such
as you say good morning if it is a time in a certain range, you say good
afternoon for a different range of times and so on. In order to move towards a more complete listing of options we need if (expression) else if (expression) control structures.
This syntax augments what we had previously. You do not need to include the final else segment. If there is only a single code statement after any if (expression), else if (expression) and/or the else, there don't need to be any braces in that section of code. Some Verbal Examples. We will start with some relatively common language examples and then progress to computer code.
Well, this can go on and on. Obviously, some of these depend on having other sources for inputs. A Simple Code Example. Now I will present a simple application to obtain two numbers from a user and tell them which is greater than the other or whether they are equal. You should call the file NumberComparison.java. |
import javax.swing.JOptionPane; public class NumberComparison {
} // end class NumberComparison |
This code can be considered to be in three sections.
Though the last section has one decision control structure nested within
another.
The next webpage contains something analogous to this if-else-else if structure, but the conditions for determining which code segment executes is simpler. |