Thursday, November 24, 2011

Java Control Structures Part II

Java Control Structures

Do you want to know the secrets of Java Programming and use it for the advancement of your career in IT? Do you have problems in your Java course? Here is an instant solution for your problem. Avail the Java training package of Prof Erwin Globio and get free tips about Java Programming Secrets. For more free information about Java and Java Training visit the following sites: http://erwinglobio.sulit.com.ph/ http://erwinglobio.multiply.com/ http://erwinglobio.wordpress.com/. You may contact the Java Trainer at 09393741359 or 09323956678. Call now and be one of the Java Experts.

Why Is Repetition Needed?

There are many situations in which it is necessary to repeat a set of statements.  For example, when a certain formula is going to be used several times (obtaining an average of grades for students in a class).  Java has three repetition, or looping, structures that let you repeat statements over and over again until certain conditions are met: while, for, and do…while.


while Looping (Repetition) Structure

The reserved word while can be used to repeat a set of statement until a certain condition is met.  The syntax for the while loop is:

            while (expression)
                      statement

The expression, called a loop condition, acts as a decision-maker and is a logical expression. The statement is called the body of the loop. Moreover, the statement can be either a simple or compound statement.
The expression provides an entry condition. If it initially evaluates to true, the statement executes. The loop condition—the expression—is then reevaluated. If it again evaluates to true, the statement executes again. The statement (body of the loop) continues to execute until the expression is no longer true.

A loop that continues to execute endlessly is called an infinite loop.

A variable in the loop condition that is used to determine whether the body of the loop will execute is called a loop control variable.

Counter-Controlled while Loops

When you know exactly how many times certain statements need to be executed, the while loop assumes the form of a counter-controlled while loop.  To do this, you set up a counter that is initialized to 0 before the while statement and then increment the counter in the while statement to keep track of how many times the body has been executed.  The syntax for a counter-controlled while loop is:

int N = some value either inputted by the user, or some specified value;
int counter = 0;
while (counter < N)
{
    statements
   
    counter++;
}

Sentinel-Controlled while Loops

You might not know exactly how many times a set of statements needs to be executed, but you do know that the statements need to be executed until a special value is met. This special value is called a sentinel.

In such cases, you read the first item before entering the while statement. If this item does not equal the sentinel, the body of the while statement executes. The while loop continues to execute as long as the program has not read the sentinel. Such a while loop is called a sentinel-controlled while loop.  The syntax for the sentinel-controlled while loop is:

input first data item into variable;
while (variable != sentinel)
{
            .
            .
            .
     input a data item into variable;
}

Flag-Controlled while Loops

Using a boolean value to control a while loop (called a flag variable) is called the flag-controlled while loop.  The syntax for this loop can be similar to the following:

boolean found = false; 
while(!found)
{
            .
            .
     if(expression)
         found = true;
            .
            .
}


EOF-Controlled while Loops

If the data file is frequently altered (for example, if data is frequently added or deleted), it’s best not to read the data with a sentinel value. Someone might accidentally erase the sentinel value or add data past the sentinel. Also, the programmer sometimes does not know what the sentinel is. In such situations, you can use an EOF (End Of File)-controlled while loop.

In Java, the form of the EOF-controlled while loop depends on the type of stream object used to input data into a program. It now follows that a general form of the EOF-controlled while loop that uses the Scanner object console to input data is of the following form:

while (console.hasNext())
{
// Get the next input (token) and store it in an appropriate variable.

// Process the data.
}

If the input source is a file, the condition might be something like infile.hasNext(), rather than console.hasNext().


Teaching Tip

In the Windows console environment, the end-of-file marker is entered using Ctrl+z. (Hold the Ctrl key and press z.) In the UNIX environment, the end-of-file marker is entered using Ctrl+d. (Hold the Ctrl key and press d.)



More on Expressions in while Statements

There are situations where the expression in the while statement may be controlled by multiple variables.  In such cases, relational operators are often used to create more complex logical conditions.

Programming Example: Checking Account Balance

This program calculates a customer’s checking account balance at the end of the month.  The input to this program is a file consisting of the customer’s account number, account balance at the beginning of the month, and each transaction (type and amount) made by the customer.  The transactions can be withdrawals (subtracted from balance), interest (added to balance), and deposits (added to balance). The data is in a specific format.

The output consists of the account number, beginning balance, ending balance, total interest paid, total amount deposited and number of deposits made, total amount withdrawn and number of withdrawals made.  The output must also be in the specified format.

The solution to this example consists of declaring and initializing variables and objects.  A Scanner object and Filereader object are used to read in data from the file based on the format.  Once the transaction codes are read in, a switch statement is used to determine what the code does and whether the amount it is associated with should be added or subtracted from the balance. An EOF-controlled while loop is used to make sure all the data is read in and put through the switch statement. Finally, the output is printed to a file using a PrintWriter object.




Programming Example: Fibonacci Number

A Fibonacci number, part of a Fibonacci sequence:

1, 1, 2, 3, 5, 8, 13, 21, 34, …

can be found using the following formula:

an = an-1 + an-2

This program determines the nth Fibonacci number given the first two.

The input to this program is first two Fibonacci numbers and the position in the sequence of the desired Fibonacci number (n).

The output to this program is the nth Fibonacci number.

The solution consists of prompting the user to enter Fibonacci number 1, Fibonacci number 2, and the n, so that Fibonacci number n can be calculated.  The first Fibonacci number is stored in the variable previous1, the second Fibonacci number is stored in the variable previous2, and the n is stored in the variable nth Fibonacci.

If…else statements are used to check if the first or second Fibonacci number is the desired number, if it isn’t the following while loop is entered to determine the number in the nth position:

counter = 3; //you already know the first and second number so you are starting with the third
while(counter <= nthFibonacci)
{ 
    current = previous2 + previous1;
    previous1 = previous2;
    previous2 = current;
    counter++;
}

The final answer will be stored in current. 


The for Looping (Repetition) Structure

The Java for looping structure is a specialized form of the while loop. Its primary purpose is to simplify the writing of counter-controlled loops. For this reason, the for loop is typically called a counted or indexed for loop.


The general form of the for statement is:

for (initial statement; loop condition; update statement)
   statement

The initial statement, loop condition, and update statement are called for loop control statements.

The for loop executes as follows:

1.      The initial statement executes
2.      The loop condition is evaluated.  If the loop condition evaluates to true:
a.       Execute the for loop statement.
b.      Execute the update statement.
3.      Repeat Step 2 until the loop condition evaluates to false.

The initial statement usually initializes a variable (called the for loop control, or indexed variable).

Some additional comments on for loops follow:

  • If the loop condition is initially false, the loop body does not execute.

  • The update expression, when executed, changes the value of the loop control variable (initialized by the initial expression), which eventually sets the value of the loop condition to false. The for loop executes indefinitely if the loop condition is always true.

  • If you put a semicolon at the end of a for statement (just before the body of the loop), the action of the for loop is empty.

  • In a for statement, if the loop condition is omitted, it is assumed to be true.

  • In a for statement, you can omit all three statements—initial statement, loop condition, and update statement. The following is a legal for loop:

for (;;)
                            System.out.println("Hello");

This is an infinite for loop, continuously printing the world Hello.


Programming Example: Classify Numbers

This program reads a given set of integers and prints the number of odd and even integers, as well as the number of zeros. 

The input to this program is 20 integers (positive, negative, and zeros) but the number of integers read can be easily modified.

The output is the number of zeros, even numbers, and odd numbers.

The solution consists of using a for loop to get and evaluate 20 numbers from the user.  Each number is put through a switch structure with cases depending on the remainder if the number is divided by 2.  If the number is even the number of evens is incremented, if the number is 0, the number of zeros is incremented, and if the number is odd count is incremented.  


The do…while Looping (Repetition) Structure

The third type of looping or repetition structure uses the reserved words do and while, and is called the do…while loop.  The syntax of this loop is:

do{
   statement(s);
}
while(expression);

The expression is called the loop condition.

The statement executes first, and then the expression is evaluated. If the expression evaluates to true, the statement executes again. As long as the expression in a do...while statement is true, the statement executes. To avoid an infinite loop, you must make sure that the body of the loop contains a statement that ultimately makes the expression evaluate to false and assures that it exits properly.

In a while or for loop, the loop condition is evaluated before executing the body of the loop. Therefore, while and for loops are called pre-test loops. On the other hand, the loop condition in a do...while loop is evaluated after executing the body of the loop. Therefore, do...while loops are called post-test loops.


break and continue Statements

The break and continue statements alter the flow of control in a program. The break statement is typically used for two purposes:

1.      To exit early from a loop
2.      To skip the remainder of a switch structure

After the break statement executes, the program continues to execute with the first statement after the structure.

The break statement can be placed within an if statement in the loop.  If the certain condition is found, the loop will be exited immediately.  This is similar to changing the value of a flag variable in an if statement within a flag-controlled loop.

The continue statement is used in while, for, and do...while structures. When the continue statement is executed in a loop, it skips the remaining statements in the loop and proceeds with the next iteration of the loop. In a while and do...while structure, the expression (that is, the loop-continue test) is evaluated immediately after the continue statement. In a for structure, the update statement is executed after the continue statement, and then the loop condition (that is, the loop-continue test) executes. 


Teaching Tip

The continue statement cannot be used in a switch statement.



Teaching Tip

In a while loop, when the continue statement is executed, if the update statement appears after the continue statement, the update statement is not executed. In a for loop, the update statement always executes.



Teaching Tip

Java also supports labeled break and labeled continue statements.  For more information, see:



Nested Control Structures

Nesting of control structures provides new power, subtlety, and complexity. if, if…else, and switch structures can be places within while loops.  For loops can be found within other for loops as in the following example:

for(int i = 1; i <= 5; i++)
{
     for(int j = 1; j <= I; j++)
            System.out.print(“*”);

     System.out.println();
}

Analysis of this program will show how the outer loops provides the limiting condition for the inner loop which controls the number of stars printed during each iteration.



The final output of this program is:

*
**
***
****
*****

Do you want to know the secrets of Java Programming and use it for the advancement of your career in IT? Do you have problems in your Java course? Here is an instant solution for your problem. Avail the Java training package of Prof Erwin Globio and get free tips about Java Programming Secrets. For more free information about Java and Java Training visit the following sites: http://erwinglobio.sulit.com.ph/ http://erwinglobio.multiply.com/ http://erwinglobio.wordpress.com/. You may contact the Java Trainer at 09393741359 or 09323956678. Call now and be one of the Java Experts.

Java Control Structures Part I

Do you want to know the secrets of Java Programming and use it for the advancement of your career in IT? Do you have problems in your Java course? Here is an instant solution for your problem. Avail the Java training package of Prof Erwin Globio and get free tips about Java Programming Secrets. For more free information about Java and Java Training visit the following sites: http://erwinglobio.sulit.com.ph/ http://erwinglobio.multiply.com/ http://erwinglobio.wordpress.com/. You may contact the Java Trainer at 09393741359 or 09323956678. Call now and be one of the Java Experts.

Control Structures

There are three ways to process a computer program. 

  1. In a sequence (executing statements in order)

  1. By making a selection or choice (branching) based on certain conditions (conditional statements)

  1. Repeating statements a certain number of times (looping)

Conditional statements can be created using the word if.  A condition is met if it evaluates to true and then certain statements are executed.  If it evaluates to false other statements are executed.


Relational Operators

In Java, a condition is represented by a logical (Boolean) expression (an expression that has a value of true or false when evaluated).  These expressions are created using relational operators (a binary operator consisting of two operands) and can be used to make comparisons.  Some relational operators in Java include:

==        equal to          
!=         not equal to
<          less than
<=        less than or equal to
>          greater than
>=        greater than or equal to

Relational Operators and Primitive Data Types

Relational operators can be used with integral and floating-point primitive data types.  For char values, whether an expression evaluates to true or false depends on the collating sequence of the Unicode character set.  When Java evaluates a logical expression, it returns the Boolean value true if the expression evaluates to true and false otherwise.


Comparing Strings

In Java, strings are compared character by character, starting with the first character and using the collating sequence. The character-by-character comparison continues until one of three conditions is met: a mismatch is found, the last characters have been compared and are equal, or one string is exhausted.

If two strings of unequal length are compared, and they are equal until the last character of the shorter string, then the shorter string is evaluated as less than the larger string. 

The method compareTo in the class String can be used to compare objects of the class.  This expression returns an integer value as follows:

Str1.compareTo(str2) = integer value less than 0 if string str1 less than string str2
Str1.compareTo(str2) = 0 if string str1 equal to string str2
            Str1.compareTo(str2) = integer value greater than 0 if string str1 greater than string str2

The method equals can be used to compare two strings and determine if they are equal.

Logical (Boolean) Operators and Logical Expressions

Logical (Boolean) operators enable you to combine logical expressions.  The three logical (Boolean) operators in Java are:

!           not       (unary)
&&      and      (binary)
||           or         (binary)

Logical operators take only logical values as operands and yield only logical values as results.

When you use the not operator, !true is false and !false is true.  Putting ! in front of a logical expression reverses the value of that logical expression.

&& and || are used to evaluate a combination of expressions.  An expression using && only returns true if ALL expressions are true.  || returns true as long as one expression in the combination is true.


Order of Precedence

Logical expressions have the following order of precedence when evaluating expressions:

Operators                                            Precedence
!  +  -  (unary operators)                      first
*  /  %                                                  second
+  -                                                       third
<  <=  >=  >                                         fourth
==  !=                                                  fifth
&&                                                      sixth
||                                                           seventh
= (assignment operator)                      last

Relational and logical operators are evaluated from left to right; their associativity is from left to right.




Short-Circuit Evaluation

Logical expressions in Java are evaluated using a high efficient algorithm known as short-circuit evaluation.  With short-circuit evaluation, the computer evaluates the logical expression from left to right. As soon as the value of the entire logical expression is known, the evaluation stops.


Teaching Tip

The operators & and | can be used in place of && and ||, respectively.  There is no short-circuit evaluation with these operators.


boolean Data Type and Logical (Boolean) Expressions

You can manipulate logical (Boolean) expressions using the boolean data type and Java reserved words boolean, true and false.


One-Way Selection

In Java, one-way selections are incorporated using the if statement. The syntax of one-way selection is:

if (expression)
    statement

The expression, which is a logical expression, is referred to as the decision maker because it decides whether to execute the statement (called the action statement).


Two-Way Selection

To choose between two alternatives Java provides the if...else statement. Two-way selection uses the following syntax:

if (expression)
    statement1
else
    statement2

If the value of the expression is true then statement1 executes; otherwise statement2 executes.  The else statement must follow an if statement; it does not exist on its own in Java.


Compound (Block of) Statements

The if and if...else structures control only one statement at a time. To permit more complex statements, Java provides a structure called a compound statement or block of statements.  Block statements are enclosed in curly braces {} and consist of a sequence of statements to be executed depending on the evaluation of the if and if…else expressions.


Multiple Selections: Nested if

You can include multiple selection paths in a program by using an if...else structure, if the action statement itself is an if or if...else statement. When one control statement is located within another, it is said to be nested. Nested statements help solve problems that require the implementation of more than two alternatives. 

In a nested if statement, Java associates an else with the most recent incomplete if—that is, the most recent if that has not been paired with an else.




Comparing if...else Statements with a Series of if Statements

A series of if statements can be used in place of if…else statements to complete a task.  However, the program may execute more slowly in this case because there are more evaluations to be made.


Conditional Operator (? :)

Certain if...else statements can be written more concisely by using Java’s conditional operator. The conditional operator, written as ?:, is a ternary operator, which means that it takes three arguments. The syntax for using the conditional operator is:

expression1 ? expression2 : expression3

If expression1 evaluated to true, the result of the conditional expression is expression2. Otherwise, the result of the conditional expression is expression3.


switch Structures

The second selection structure in Java does not require the evaluation of a logical expression. It is called the switch Structure and gives the computer the power to choose from many alternatives.  The switch statement has the following syntax:

            switch(expression)
            {
                        case value1: statements1
                                           break;
                        case value2: statements2
                                           break;
                        …
                        case valuen; statementsn
                                           break;
                        default: statements
            }

The expression (sometimes called the selector) is evaluated first and the value of the expression is then used to perform the actions specified in the statements that follow the reserved word case. 

The expression is usually an identifier and the value is always an integral.  The value of the expression determines which statement is selected for execution, therefore a particular case values must be unique. 

One or more statements may follow a case symbol, and curly braces are unnecessary to group them. 

The break statement may or may not appear after each statement. 

A switch statement executes according to the following rules:

  1. When the value of the expression is matched against a case value (also called a label), the statements execute until either a break statement is found or the end of the switch structure is reached.

  1. If the value of the expression does not match any of the case values, the statements following the default label execute. If the switch structure has no default label, and if the value of the expression does not match any of the case values, the entire switch statement is skipped.

  1. A break statement causes an immediate exit from the switch structure.


Choosing Between an if...else and a switch Structure

No fixed rules exist that can be applied to decide whether to use an if...else structure or a switch structure to implement multiple selections, but you should remember the following considerations:

 If multiple selections involve a range of values, you should use either an if...else structure or a switch structure, wherein you convert each range to a finite set of values.

If the range of values is infinite and you cannot reduce them to a set containing a finite number of values, you must use the if...else structure.





Do you want to know the secrets of Java Programming and use it for the advancement of your career in IT? Do you have problems in your Java course? Here is an instant solution for your problem. Avail the Java training package of Prof Erwin Globio and get free tips about Java Programming Secrets. For more free information about Java and Java Training visit the following sites: http://erwinglobio.sulit.com.ph/ http://erwinglobio.multiply.com/ http://erwinglobio.wordpress.com/. You may contact the Java Trainer at 09393741359 or 09323956678. Call now and be one of the Java Experts.