If (expression) Code Segments
In almost all instances, when writing computer code, developers are going
to want the code's execution to depend on other things such as user
selections or other internal computations. The following list
contains a very few of the sorts of situations where this might arise.
Obviously, this list can go on and on. In order for these sorts of decisions to be made within computer code, computer languages have built-in constructs for control of the program flow. That is, the programming languages have built-in control structures to allow determination of what code will execute based on other inputs. While there are all kinds of control structures, in this webpage we will focus on one of the most fundamental, if (expression) code segments.
In general the syntax for this sort of control structure looks like the following.
The code between the braces will execute only if the (expression) evaluates as true. The expression must be contained within parentheses.
If there is only a single code statement after the if (expression) there doesn't need to be any braces.
This isn't really any different than the If - Then 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.
Many programmers, and I strongly encourage you to do so, use some sort of indentation to help them when debugging. Code can get complicated and determining what belongs in what blocks of code can become very difficult!
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. Since we have been somewhat shortchanging your experience with applets we will develop another applet. This applet will do very little other than ask the user to enter a number within a particular range. If they do it they will get a message that they have done so. You should call the applet NumberRangeApplet.java.
public class NumberRangeApplet extends JApplet
} // end class NumberRangeApplet
|The html file should be NumberRangeApplet.html.|
|<APPLET CODE="NumberRangeApplet.class" WIDTH=200 HEIGHT=100> </APPLET>|
|Since we will use this construct so much throughout the
course I will not present another example in this webpage.
The next webpage will improve on this example somewhat by doing a better job of dealing with the situation where the user doesn't input a number in the appropriate range. This will involve using else clauses in our If (expression) code segments.