Chapter 4

Control Structures I

Chapter Overview

In this chapter, students will learn about control structures if, if else and switch. They will learn how to incorporate these into programs to enable them to make decisions, as opposed to simply executing statements in a sequential order.

Chapter Objectives

In this chapter, students will:

· Learn about control structures

· Examine relational and logical operators

· Explore how to form and evaluate logical (Boolean) expressions

· Learn how to use the selection control structures if, if…else, and switch in a program

Control Structures

There are three ways to process a computer program.

1. in sequence (executing statements in order)

2. by making a selection or choice (branching) based on certain conditions (conditional statements)

3. repeating statements a certain number of times (looping)

èfrom OHP pg3:

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.

è from OHP pg 7:


èfrom Book pg151:

public class FloatingPointNumbers

{

public static void main(String[] args)

{

System.out.println("3.0 / 7.0 = " + (3.0 / 7.0));

System.out.println("2.0 / 7.0 = " + (2.0 / 7.0));

System.out.println("3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0 = "

+ (3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0));

}

}

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 either a mismatch is found or the last characters have been compared and are equal.

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:

an integer value less than 0 if string str1 is less than string str2

Str1.compareTo(str2) = { 0 if string str1 is equal to string str2

an integer value greater then 0 if string str1 is greater than string str2

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

èfrom Book pg 153:

String str1 = "Hello";

String str2 = "Hi";

String str3 = "Air";

String str4 = "Bill";

String str5 = "Bigger";

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)

When you use the not operator !true is false and !false is true. & 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.

èfrom OHP pg9:

Order of Precedence

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

Operators / Precedence
! + - (unary operators) / first
* / % / second
+ - (in expression) / 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.

èfrom Book pg160:

//Chapter 4: Logical operators

public class LogicalOperators{

public static void main(String[] args)

{

boolean found = true;

boolean flag = false;

int num = 1;

double x = 5.2;

double y = 3.4;

int a = 5, b = 8;

int n = 20;

char ch = 'B';

System.out.println("Line 1: !found evaluates to " + !found); //Line 1

System.out.println("Line 2: x > 4.0 evaluates to "+ (x > 4.0)); //Line 2

System.out.println("Line 3: !found & (x >= 0) " + "evaluates to "

+ (!found & (x >= 0))); //Line 3

System.out.println("Line 4: !(found & (x >= 0)) " + "evaluates to "

+ !(found & (x >= 0))); //Line 4

System.out.println("Line 5: x + y <= 20.5 evaluates to "

+ (x + y <= 20.5)); //Line 5

System.out.println("Line 6: (n >= 0) & (n <= 100) " + "evaluates to "

+ ((n >= 0) & (n <= 100))); //Line 6

System.out.println("Line 7: ('A' <= ch & ch <= 'Z') " + "evaluates to "

+ ('A' <= ch & ch <= 'Z')); //Line 7

System.out.println("Line 8: (a + 2 <= b) & !flag "+ "evaluates to "

+ ((a + 2 <= b) & !flag)); //Line 8

}

}

Logical expressions in Java are evaluated using a high efficient algorithm known as short-circuit evaluation. The computer evaluated the logical expression from left to right and as soon as the value of the entire expression is known, the evaluation stops. For example, when evaluating an expression is using the || operator and the first part of the expression is true, the rest does not have to be evaluated.

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

Quick Quiz

1. True or False: The == operator is used to assign a value to a variable.

Answer:

2. The operator || is the logical operator ____.

Answer:

3. True or False: A relational operator allows you to make comparisons in a program.

Answer:

4. What is the value of the expression: (10 >= 5) & (‘B’ < ‘C’)

Answer:

5. With short-circuit evaluation, when the value of an entire expression is found, evaluation ____.

Answer:

Selection: if and if…else

In Java, there are two selection or branch control structures: if statements and switch structures.

if statements can be used in one-way selection. 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).

è from OHP pg14

èfrom Book pg165

//Determine the absolute value of an integer

import javax.swing.JOptionPane;

public class AbsoluteValue

{

public static void main(String[] args)

{

int number;

int temp;

String numString;

numString =

JOptionPane.showInputDialog("Enter an integer:"); //Line 1

number = Integer.parseInt(numString); //Line 2

temp = number; //Line 3

if(number < 0) //Line 4

number = -number; //Line 5

JOptionPane.showMessageDialog(null,

"The absolute value of " + temp

+ " is " + number,

"Absolute Value",

JOptionPane.INFORMATION_MESSAGE); //Line 6

System.exit(0);

}

}

if…else statements can be used in two-way selections. The syntax for two-way selections is as follows:

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.

èfrom OHP pg16

è from Book pg169

//Chapter 4: Weekly Wages

import java.io.*;

import java.text.DecimalFormat;

public class WeeklyWages

{

static BufferedReader keyboard = new

BufferedReader(new InputStreamReader(System.in));

public static void main(String[] args) throws IOException

{

double wages, rate, hours; //Line 1

DecimalFormat twoDigits = new DecimalFormat("0.00"); //Line 2

System.out.print("Line 3: Enter working hours: "); //Line 3

hours = Double.parseDouble(keyboard.readLine()); //Line 4

System.out.println(); //Line 5

System.out.print("Line 6: Enter pay rate: "); //Line 6

rate = Double.parseDouble(keyboard.readLine()); //Line 7

System.out.println(); //Line 8

if(hours > 40.0) //Line 9

wages = 40.0 * rate +

1.5 * rate * (hours - 40.0); //Line 10

else //Line 11

wages = hours * rate; //Line 12

System.out.println("Line 13: The wages are $"

+ twoDigits.format(wages)); //Line 13

String ch1;

System.out.println("Press the ENTER key to continue");

ch1 = keyboard.readLine();

}

}

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.

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 nested if statements, Java associates an else with the most recent incomplete if.

èfrom OHP pg18

•  Syntax

if(expression1)

statement1

else

if(expression2)

statement2

else

statement3

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.

Certain if…else statements can be written more concisely by using Java’s conditional operator (?:). This operator 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 break statement results in immediate exit from the switch structure. If the value of the expression does not match any of the case statements, the statements following the default label execute. If there is no default label in this case, the switch statement is skipped.

è from OHP pg21

è From book pgf179

//Chapter 4: Effect of break statements in a switch structure

//Effect of break statements in a switch structure

import java.io.*;

public class BreakStatementsInSwitch

{

static BufferedReader keyboard = new

BufferedReader(new InputStreamReader(System.in));

public static void main(String[] args) throws IOException

{

int num;

System.out.print("Enter an integer between "

+ "0 and 10: "); //Line 1

System.out.flush(); //Line 2

num = Integer.parseInt(keyboard.readLine()); //Line 3

System.out.println("\nThe number you entered is "

+ num); //Line 4

switch(num) //Line 5

{

case 0: //Line 6

case 1: System.out.print("Hello "); //Line 7

case 2: System.out.print("there. "); //Line 8

case 3: System.out.print("I am "); //Line 9

case 4: System.out.println("Mickey."); //Line 10

break; //Line 11

case 5: System.out.print("How "); //Line 12

case 6: //Line 13

case 7: //Line 14

case 8: System.out.println("are you?"); //Line 15

break; //Line 16

case 9: break; //Line 17

case 10: System.out.println("Have a nice day."); //Line 18

break; //Line 19

default: System.out.println("Sorry the number is out "

+ "of range."); //Line 20

}

System.out.println("Out of switch structure."); //Line 21

}

}

èPls make a revision from pg 183-189

Programming Example: Cable Company Billing

This programming example demonstrates a program that calculates a customer’s bill for a local cable company. There are two types of customers (residential and business) and two rates for calculating their cable bills.

The input to the program is the customer’s account number, customer code, number of premium channels to which the customer subscribes, and, in the case of business customers, number of basic service connections.

The output to the program is the customer’s account number and the billing amount.

The solution to the example requires importing java.io and java.text.DecimalFormat. It requires asking the user for an account number (an integer) and a customer code using Integer.parseInt and readLine().charAt. It then requires the use of a switch statement based on the customer type (residential or business). if statements are used within the switch statement to determine the amount due by each customer.

èfrom book pg186

//Chapter 4: Cable Company Billing

import java.io.*;

import java.text.DecimalFormat;

public class CableCompanyBilling

{

static BufferedReader keyboard = new

BufferedReader(new InputStreamReader(System.in));

//Named constants - residential customers

static final double R_BILL_PROC_FEE = 4.50;

static final double R_BASIC_SERV_COST = 20.50;

static final double R_COST_PREM_CHANNEL = 7.50;

//Named constants - business customers

static final double B_BILL_PROC_FEE = 15.00;

static final double B_BASIC_SERV_COST = 75.00;