Saturday, May 7, 2011

BASIC CONTROL STRUCTURES

All programming languages provide ways to alter the sequence of instructions that actually get
executed when a program runs. This ability to select which logic to apply, or to choose an appropriate
number of times to cycle through a section of code, is what makes programs flexible enough to be
useful in the real world. Imagine a program to compute the average grades for students in a class,
but imagine that the program requires all classes to have exactly the same number of students, and
has no way to properly handle a missing grade! Such a rigid program would not be worth the trouble
to write.
if
The most common control structure for selecting a block of code to execute is the if statement. The if
statement can be used in its simple form, or in its extended if-else form. Here is an example of a simple
if statement:
if(grade > 0) {
sumOfGrades = sumOfGrades + grade;
numberOfGrades++;
}
This statement says, if the variable grade is greater than 0, then add the grade value to the variable
sumOfGrades, and increment the variable numberOfGrades by 1. Otherwise, do nothing. Either both
statements following the if statement will be executed, or neither will be, because they are both within the
curly brackets which follow the if. The curly brackets mark a code block.
If the tested condition is true, then the code block of the if statement will be executed. If the condition
is false, the code block will be skipped.
Here is the syntax of the simple if statement:
if( <conditional expression> ) <statement>
The conditional expression must evaluate to either true or false. If the conditional expression is true,
the following statement will be executed, but not otherwise. The <statement> can also be a compound
statement, which is another way of saying that <statement> can be a code block enclosed in curly braces.
A compound statement or code block is enclosed in curly braces, and each statement inside must be terminated
with a semicolon.
Here is an example of an if-else statement:
if( windSpeed > 20 ) {
hoistSmallSail();
}
else {
hoistLargeSail();
}
The if-else statement allows the program to select one of two mutually exclusive paths of execution. In
this case, if the wind is strong, the program calls a method to hoist a small sail. Otherwise, the program calls a
method to hoist a large sail. By the way, you can tell that hoistSmallSail() and hoistLargeSail()
are methods because a pair of parentheses follows the name. A method is a named block of code, and we will
talk about methods when we discuss classes and objects in more detail later.
Here is the syntax of the if-else statement:
if( <conditional expression> ) <statement_one>
else <statement_two>
If the conditional expression is true, statement_one will be executed. If the conditional statement is
false, statement_two will be executed. As before, statement_one and statement_two can be
compound statements, i.e., code blocks framed in curly braces.
for
Programs frequently must iterate or loop through a block of code repeatedly. Java has several control structures
for this purpose, and one of the most commonly used control structures of this type is the for loop.
Suppose we want to compute the average grade in a class of students. We have the scores in a file
called Students, and each line in the file contains a single score. Each score is the grade of one of the students
(e.g., 89.5). We could write code such as this to read the scores from the file and compute the total of
all the scores:
double total = 0.0;
BufferedReader in = new BufferedReader(
new FileReader( "Students" ) );
for ( int i = 1; i <= numberOfStudents; i++ ) {
String score = in.readLine();
total = total + Double.parseDouble( score );
The first line declares a thing called a BufferedReader, which is “wrapped around” a FileReader
that opens the file called Students. We will discuss these sorts of input/output statements further in the
section on Input and Output. This statement declares the variable in to be a BufferedReader associated with
the file Students.
Notice that programming statements in Java can continue to a second, third, or more lines. The Java
compiler will continue to interpret the lines as one statement until it encounters the semicolon, which marks the
end of the statement.
The for statement begins with parentheses enclosing three expressions, which are separated by semicolons.
The first expression defines initial conditions in the for loop. In this case, the expression declares an
int called i, and sets the value of i to 1.
The second expression in the for statement establishes a condition which will evaluate to either true or
false. When the condition is true, the code block of the for statement will be executed. In this case, as long as
the value of i is less than or equal to the number of students, the loop will execute.
The third expression in the for statement specifies what to change each time the loop is executed. This
expression is sometimes called the “increment expression,” because it is usually employed to change the value
of the variable being tested in the second expression. That is the case here, because the third expression says to
increment the value of the variable i each time the loop executes.
The body or code block of the for statement follows the three expressions within parentheses. In this case,
the readLine() method of the BufferedReader reads the next line of the file into a String variable
called score. Since the BufferedReader reads character strings, we must convert the characters into an
internal floating-point number before we can do our math. The last line says use the parseDouble() method
of the Double class to interpret the character string in score (e.g., 89.5) as a double (a floating-point
number which can include a fractional part). The Double class is one of Java’s “wrapper classes,” which we
discussed in the section on data types.
In summary, this for loop will begin executing with the value of i set to 1. After each execution of the
loop, the value of i will be incremented. The loop will continue to execute as long as the value of i is no greater
than the number of students. When i becomes greater than the number of students, the conditional test in the
second expression of the for statement will fail (will be false), and the program will “drop out” of the loop and
continue at the next statement following the for loop body.
Here is the syntax of the for statement:
for( <initial>; <test condition>; <increment> ) <body>
The conditional expression must evaluate to either true or false. If the conditional expression is true, the
body of the for loop will be executed, but not otherwise. The <body> is usually a compound statement, which
is a code block enclosed in curly braces. Each statement within the body must be terminated with a semicolon.
while
Another structure to control looping (iteration) is the while statement. Suppose we don’t know how many
student scores are in the file of student scores. We can use a while statement to read the file until there are no
more scores in the file to be read:
double total = 0.0;
BufferedReader in = new BufferedReader(
new FileReader( "Students" ) );
String score = in.readLine();
while( score != null ) {
total = total + Double.parseDouble( score );
score = in.readLine();
 We use the same BufferedReader as before to read the file Students. After reading the first line in
the file, the while statement checks to see if the variable score has a value of null. The variable score will
be null only if there was nothing in the file to read. As long as score is not null, the body of the while statement
will execute—it will “parse,” or interpret, as a fractional number, whatever the BufferedReader just
read, and then it will read the next line in the file.
The while statement syntax is very simple:
while( <loop condition> ) <statement>
Again, the statement can be a code block enclosed in curly braces. As long as the test condition remains
true, the body of the while statement continues to execute. This is a very appropriate control structure when
we do not know in advance how many times a code block must execute.
do-while
A variation of the while statement is the do-while. In the case of the do-while statement, the body
of the loop executes before the code checks the loop condition. When a program must execute a block of code
at least once, the do-while may be the best choice for controlling a loop. Here is code to use the do-while
statement instead of the while statement for reading the file Students:
BufferedReader in = new BufferedReader(
new FileReader( "Students" ) );
String score;
do {
score = in.readLine();
total = total + Double.parseDouble( score );
} while( score != null )
At first glance, it looks like this version saves code. However, in this particular case, this code exposes us
to danger. If the file should ever be empty, the first call to parseDouble will cause the program to fail with
a run-time exception, because Double.parseDouble cannot parse a null value. In this application, we
would do better to use the while instead of the do-while.
This is the syntax of the do-while loop:
do <loop body>
while( <loop condition> );
The loop body can be, and usually is, a code block framed by curly braces. As long as the loop condition
remains true, the loop body will execute again and again. The do-while structure is particularly appropriate
when you require the loop body to execute at least once every time the program runs.
switch
The last control structure we will discuss here is the switch statement. Like the if statement, the
switch statement allows your program to select certain statements to execute under certain conditions. The
switch statement is more complex, and one can always use a series of if statements instead of a switch
statement, but switch is very appropriate and readable for some programming problems.
Suppose we have a group of students and want to assign them to different dorms depending upon whether
they are freshmen, sophomores, juniors, or seniors. Let’s assume that the variable yearInSchool is coded
as an int, and is set to 1 for freshmen, 2 for sophomores, 3 for juniors, and 4 for seniors. We could then use
this code to decide to which dorm each student should be assigned:

switch( yearInSchool ) {
case 1: System.out.println( "Oberlies Hall" );
break;
case 2: System.out.println( "Kiriazides Hall" );
break;
case 3: System.out.println( "Glisson Dorm" );
break;
case 4: System.out.println( "Valk Hall" );
break;
default: System.out.println( "illegal year" );
}
If a student is a freshman, the student will be assigned to Oberlies Hall; if the student is a sophomore, the
student will be assigned to Kiriazides Hall; etc.
Notice the break statements. The break statement says to exit the switch statement. If the break
statement is missing, the execution of the switch statement will “fall through” to the next case. Sometimes
you will want that to happen, but certainly not always. Forgetting to insert the break statement appropriately
is a common programming error.
Here’s an example using the switch statement to allow “falling through” from one condition to the next
in a helpful way:
switch( dayOfChristmas ) {
case 12: System.out.println( "Twelve drummers drumming" );
case 11: System.out.println( "Eleven pipers piping" );
case 10: System.out.println( "Ten lords a-leaping" );
case 9: System.out.println( "Nine ladies dancing" );
case 8: System.out.println( "Eight maids a-milking" );
case 7: System.out.println( "Seven swans a-swimming" );
case 6: System.out.println( "Six geese a-laying" );
case 5: System.out.println( "Five golden rings" );
case 4: System.out.println( "Four calling birds" );
case 3: System.out.println( "Three French hens" );
case 2: System.out.println( "Two turtle doves" );
case 1: System.out.println( "And a partridge ... tree" );
break;
default: System.out.println( "?Day = " + dayOfChristmas );
}
Notice that in this example, the case statements proceed from highest to lowest, instead of the other way
around. The cases can be ordered in any way that makes sense, even nonsequentially. The switch statement
executes by taking the value of the integral expression inside the parentheses (assume that dayOfChristmas
is an int). The switch statement then compares the value of the integral expression to each case value.
When it finds a match, the code for that case begins to execute.
In this example, the switch statement helps us write the lyrics for the song The Twelve Days of Christmas.
For instance, if the dayOfChristmas equals 3, execution will begin at case 3 and continue until it encounters
the break at the end of case 1. The one break statement is necessary to avoid executing the default
error message. The result will be the lyrics for the third day of Christmas:
Three French hens
Two turtle doves
And a partridge in a pear tree

Here is the syntax for the switch statement:
switch( <integral expression> ) {
case value_one: <statement_one>
case value_two: <statement_two>
case value_three: <statement_three>
. . .
case value_n: <statement_n>
default: <statement_default>
}
The integral expression must evaluate to an integer value. This usually means that the integral expression
is an int or a char value. In particular, the expression cannot be a String (although that option would be
nice to have sometimes).
The statements can be compound statements, and in a “switch” from other syntax, compound statements
within a switch case need not be framed in curly brackets. However, if you like curly brackets, the Java
compiler will accept curly brackets around the compound statements.
The default case is optional, but we believe a default case should always be included, if only to
provide error checking. If your program expects the days of Christmas to vary between 1 and 12, it’s good
practice to put in a default statement which will let you know if the value of dayOfChristmas ever turns
up as some value other than 1 through 12. Especially with more complex programs, such default code could
save you many hours of debugging. Without the default statement, if none of the cases match the integral
expression, the JVM simply skips over all the switch code. Having the default case will catch the
anomalous condition and show you where the problem is.
Here is a complete program to print the words to the 12 verses of The Twelve Days of Christmas. The program
uses a while loop to iterate through the 12 verses. Then it uses an if-else statement to decide whether this
is the first verse or one of the later verses; that is necessary because the line about a partridge in a pear tree has
the word “And” in it for the 2nd through 12th verses, but not for the 1st verse. The \n at the end of the lines
having to do with a “partridge in a pear tree” is an example of an escape sequence. An escape sequence begins
with a backslash, and the following character has special meaning for the Java compiler. The \n means to insert
a linefeed, so that there will be a blank line between verses. There are other escape sequences for tabbing and
other functions, too.
Finally, this program illustrates how to add comments to a program written in Java. Any typing that follows
// on a line is treated as a comment; that is, the typing is ignored by the Java compiler. Also, any typing
between the characters /* and */ is also a comment, and such comments can extend over multiple lines. If
such a multiline comment begins with /**, it is a javadoc (Java documentation) comment, and will be included
by the javadoc processor in the automatically generated documentation of the program. Javadoc
comments can include special tags, such as @author, which the javadoc processor recognizes when it
generates the HTML format of the documentation.
We will not be describing the javadoc processor in any more detail in this chapter, but you can read
about javadoc comments here: http://java.sun.com/j2se/javadoc/. In our opinion, the javadoc processor is
one of the magnificent contributions Java has made to programming practice. The javadoc processor uses
comments within the programs themselves to generate attractive and complete documentation of every
class. Wonderful!
As a matter of programming style, I like to put a comment following closing curly braces that tells me
which block of code is being terminated. Particularly when many code blocks are nested within one another,
such comments help me keep track of my curly brackets. This style is a personal preference, not a standard.
Adopt it only if you wish.
/**
* A program to print the words to the Twelve Days of Christmas
* @author Carl Reynolds
*/
public class DaysOfChristmas {
public static void main(String args[]) {
int dayOfChristmas = 1; //start with the 1st day of Christmas
while( dayOfChristmas <= 12 ) {
if( dayOfChristmas == 1 )
{
System.out.println( "A partridge in a pear tree \n" );
}//if
else
{
switch( dayOfChristmas )
{
case 12: System.out.println( "Twelve drummers drumming" );
case 11: System.out.println( "Eleven pipers piping" );
case 10: System.out.println( "Ten lords a-leaping" );
case 9: System.out.println( "Nine ladies dancing" );
case 8: System.out.println( "Eight maids a-milking" );
case 7: System.out.println( "Seven swans a-swimming" );
case 6: System.out.println( "Six geese a-laying" );
case 5: System.out.println( "Five golden rings" );
case 4: System.out.println( "Four calling birds" );
case 3: System.out.println( "Three French hens" );
case 2: System.out.println( "Two turtle doves" );
System.out.println(
"And a partridge in a pear tree \n" );
break;
default: System.out.println( "?Day = " + dayOfChristmas );
}//switch
}//else
dayOfChristmas++;
}//while
System.out.println("The End" );
}//main
}//class

No comments:

Post a Comment