If (expression) Else Code Segments
In the last webpage we developed If (expression) code segments. But
clearly, these are not sufficient for all situations. For example,
we didn't have any obvious ways to deal with users that didn't enter
numbers in the correct range. These users didn't get any interaction
from the program.
In order to move towards a more complete listing of options we need if (expression) else control structures.
This syntax augments what we had previously
If there is only a single code statement after the if (expression) and/or the else, there doesn't need to be any braces.
This isn't really any different than the If - Then- Else statements used in Visual Basic except in VB you don't need to enclose the condition in parentheses and multiple program statements within the decision block are terminated by an End If.
Some Verbal Examples. We will start with some relatively common language examples and then progress to computer code.
Another example might be
Well, this can go on and on. Obviously, some of these depend on having other sources for inputs.
A Simple Code Example. Now I want to slightly modify the NumberRangeApplet from the last web page to give some feedback to a user who incorrectly enters a number. You should call the applet NRangeElseApplet.java.
public class NRangeElseApplet extends JApplet
} // end class NumberRangeApplet
|The html file should be NRangeElseApplet.html.|
|<APPLET CODE="NRangeElseApplet.class" WIDTH=200 HEIGHT=100> </APPLET>|
|Make sure you try entering a number of different values
by using the restart option in the drop down box on the applet window.
Now we will revisit another one of our earlier examples.
Accumulating an Error Message. When we first implemented try and catch blocks for numeric inputs we ended the program as soon as a user made an error. This would be better if
So we will modify our earlier code into the following application called FloatFormatExceptions.java.
public class FloatFormatExceptions
} // end class NumberFormatExceptions
|The code can be considered to be in five major
Now we will move onto one other even somewhat more complicated decision control structure in the next webpage.