Sie sind auf Seite 1von 57

Fundamentals of Software

Development
CT010-3-1
Structured Programming Control
Structures in Java

Prepared by: JRK First Prepared on:27 th July 2005 Last Modified on:14th December 2005
Quality checked by: GTK
Copyright 2005 Asia Pacific University College of Technology and Innovation

Topic & Structure of the lesson


Structured Programming Control Structures
Operators and expressions
Conditional constructs
if..else constructs
nested if..else constructs
switch..case
break and continue statements

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Learning Outcomes
At the end of this topic, you should be able to:
Use operators in Java programs and subsequently
write expressions that make up a Java program
Create, edit, compile, run and debug simple
procedural-based Java programs using conditional
constructs.

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Operators in Java
We have completed an overview of

Data types
Next, we will look at
Operators

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Operators in Java
Java supports a rich set of operators which can be
classified into eight categories:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise operators
5. Increment/Decrement operators
6. Assignment operators
7. Conditional operators
8. Special operators

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Operators in Java
Arithmetic Operators
Java language supports the arithmetic operators as listed
below for all integer and real numbers :
Operator

Use

Description

op1 + op2

Adds op1 and op2

op1 - op2

Subtracts op1 from op2

op1 * op2

Multiplies op1 by op2

op1 / op2

DIvide op1 by op2

op1 % op2

The remainder of dividing op1 by op2

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Operators in Java
Relational
A relational operator compares 2 values and determines
the relationship between them.

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Operators in Java
Logical Operators
Relational operators are often used with logical operators to
construct more complex decision-making expressions.
Operator

Use

&&

op1 && op2

||

op1 || op2

! op

&

op1 & op2

op1 | op2

?:

expression ? op1 : op2

CT010-13-Fundamentals of Software Development

Description
op1 and op2 are both true,
conditionally
evaluates op2
Either op1 and op2 are true,
conditionally
evaluates op2
op is false
op1 and op2 are both true,
always
evaluates op2
Either op1 and op2 are true,
always
evaluates op2
Shorthand for and
if-else statement
The ?: operator evaluates expression
and returns op1 if its true and op2 if
its false

Structured Programming Control Structures in Java

Operators in Java
Bitwise Operators
Bitwise operators can be
1. Logical

2. Shift

3. Assignment operators.

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Operators in Java
Bitwise Operators
Logical operators
&
|
^
~

bitwise AND
bitwise OR
bitwise (XOR)
bitwise complement

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Operators in Java
Bitwise Operators
Shift operators
>> shift right with sign extension
>>>
shift right with zero fill
<< shift left with zero fll
General form
Value << num
Value >> num
Value >>> num

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Operators in Java
Bitwise Operators
Shift operators
Examples
1. 16 >> 2
returns 4
2. -16 >> 2
returns -4
3. 100 >>> 2
returns 25

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Operators in Java
Increment/decrement Operators
++ increase value by 1
--

decrease value by 1

Eg.
i++

OR ++i

k- -

OR - -k

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Operators in Java
Assignment Operators

Assignment operators are used to assign one value to another. Listed below
are the basic assignment operators (=) as well as the shortcut assignment
operators.

Operator

Use

Description

op1 = op2

Op1 = op2

+ =

op1 += op2

op1 = op1 + op2

- =

op1 -= op2

op1 = op1 - op2

* =

op1 *= op2

op1 = op1 * op2

/ =

op1 /= op2

op1 = op1 / op2

%=

op1 %= op2

op1 = op1 % op2

&=

op1 &= op2

op1 = op1 & op2

| =

op1 |= op2

op1 = op1 | op2

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Quick Review Question


1. Indicate what type each of the following
operator is
a. &&

- short-circuit, logical AND

b. ||
c. &
d. ^
e. |=
f. +=
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Quick Review Question


2. Use 16 bits in the following
a. 12 & 14 = ?
b. -25 >>> 3
c. -25 >> 3

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Operators in Java
We have completed an overview of

Data types and Operators


Next, we will look at
Expressions

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Expressions
Definition : An expression is a series of variables,
operators and method calls (constructed according to
the syntax of the language) that evaluates to a single
value.
Expression perform the work of a Java program.
Expressions are used to :
compute (eg. totalPrice = productCost +
shippingCost)
assign values to variables (eg. count = 10)
to help control the execution flow of a program
(eg while (count <10) count++;)
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Expressions
Basically, there are 2 types of expressions :
Expression with operators
eg.
temperature = 98;
total = (count + 10)* 25 / 4;
count++;

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Expressions
Method call expression
eg. Keyboard.readInt(),
Integer.parseInt()
A method(function) call evaluates to the return
value of the method.
The return data type of a method expression
call is the same as the data type of the return
value of that method.

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Follow Up Assignment
1. Write an expression that returns the solution
for the general form of the quadratic equation
as shown below
ax2 + bx + c = 0

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Quick Review Question


We are going to work together to write some more
Java programs that we can test in the lab.
1. Write a Java program to display the lines:
This is the first line.
This is the second line.
2. Write a Java program to
Assign the value 45.35 to the float variable price,
10 to the integer variable units and calculate and
display the total value of price * units

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


Generally, the simple form of if can be written like this:
if (expression)
statement
So, what if you wanted to perform a different set of
statements if the expression is false? Well, you can use the
else statement for that. Consider another example.
Suppose that your program needs to perform different
actions depending on whether the user clicks on the OK
button or the Cancel button in an alert window. Your
program could do this using an if statement:
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


if (conditional expression)
{
// statements when true
}
else
{
// statements when false
}

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


// response is either OK or CANCEL depending
// on the button that the user pressed
...
if (response == OK) {
...
// code to perform OK action
...
} else {
...
// code to perform Cancel action
...
}
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


Example
Social Security tax on wages is calculated as follows:

Tax = 0.124 x wages


= 0.124 x $57600

if wages <= $57600


if wages >

$57600

Write an application to accept wages, calculate and display


the Social Security tax.
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


Example 1

Tax =

0.124 x wages

if wages <= $57600

0.124 x $57600 otherwise

This computation can be expressed neatly


in Java by the if statement :
if (wages <= 57600)
tax = 0.124 * wages;
else
tax = 0.124 * 57600;
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


This computation will be embedded in the
following complete Java application with the
values 0.124 and 57600 replaced by suitably
named symbolic constants.

Tax_Calculation.java

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


import keyboard.*;
class Tax_Calculation
{
public static void main (String[] args)
{
final double MAXIMUM_WAGE = 57600, TAX_RATE = 0.124;
double wages, tax;
System.out.print("Your wages subject to Social Security Tax are : $ ");
wages=Keyboard.readInt();
if (wages <= 57600)
tax = TAX_RATE * wages;
else
tax = TAX_RATE * MAXIMUM_WAGE;
System.out.println("Your Security Tax is :$ " + tax);
}
}

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


Output:
Your wages subject to Social Security Tax are : $20000
Your Security Tax is : $2480.0
Your wages subject to Social Security
Tax are : $60000
Your Security Tax is : $7142.4

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Quick Review Question


You have seen and done the following examples:
1. Tax calculation
You should now be in a position to write a Java program
that accepts data form the keyboard, uses the select
statement and displays appropriate results.
This is your task:
Accept the temperature in degrees Fahrenheit from the
user, convert and display the temperature in degrees
Centigrade
Here is the formula to use
degree F = 5 ( F 32) / 9

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


There is another form of the else statement,
else if
which executes a statement based on another expression.
Example
Grades are assigned based on the value of a test score:
A for a score of 70% or more
B for a score of 60% or more but not in the ranges above
C for a score of 50% or more but not in the ranges above
D for a score of 40% or more but not in the ranges above
F for a score below 40%
Write an appropriate select statement

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


Example 2

Grade =

CT010-13-Fundamentals of Software Development

testscore : 70-100

testscore : 60-69

testscore : 50-59

testscore : 40-49

testscore : 0-39

Structured Programming Control Structures in Java

The if else statement


int testscore;
char grade;
if (testscore >= 70) {
grade = 'A';
} else if (testscore >= 60) {
grade = 'B';
} else if (testscore >= 50) {
grade = 'C';
} else if (testscore >= 40) {
grade = 'D';
} else {
grade = 'F';
}
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


When writing else is statements, the rule to
always remember is:
No else without parent if

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


BUG ALERT : Dangling else
Nested if statements can become quite complicated.
Indentation alone is not sufficient such as the example
below :
if (condition-1)
if (condition-2)
statement-1
else
statement-2

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


BUG ALERT : Dangling else (contd)
may be interpreted as below :
if (condition-1)
if (condition-2)
statement-1
else
statement-2
The rule is that an else is paired with the nearest
unmatched if preceding.

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


BUG ALERT : Dangling else (contd)
To get the desired effect, the programmer can either
insert a dummy else as in :
if (condition-1)
if (condition-2)
statement-1
else;
else
statement-2

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


BUG ALERT : Dangling else (contd)
Or the then clause can be enclosed in a pair of
braces :
if (condition-1) {
if (condition-2)
statement-1
}
else
statement-2

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

The if else statement


BUG ALERT : Dangling else (contd)
The best solution, however, is to reorganize the code to :
if (not condition-1)
statement-2
else if (condition-2)
statement-1
Remember to match each else with the correct if. The
rule is that an else is paired with the nearest unmatched if
preceding.

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Quick Review Question


Let us test what you have just learned:

1. Write a program segment to find the largest of


2 double numbers x and y.

2. Write a program segment to find the largest of


3 double numbers x, y and z.

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Javas switch statement


Use the switch statement to conditionally perform
statements based on some expression.

For example, suppose that your program contained


an integer named month whose value indicated the
month in some date. Suppose also that you wanted to
display the name of the month based on its integer
equivalent. You could use Java's switch statement to
perform this feat:

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Javas switch statement


int month;
...
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
}

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Javas switch statement


The switch statement evaluates its expression, in this
case, the value of month, and executes the appropriate
case statement. Of course, you could implement this as
an if statement:
int month;
...
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
...
// you get the idea
...
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Javas switch statement


switch Vs else-if : Deciding whether to use an if
statement or a switch statement is a judgment call.
You can decide which to use based on readability and
other factors. Each case statement must be unique
and the value provided to each case statement must
be of the same data type as the data type returned by
the expression provided to the switch statement.

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Javas break statement

break statements : The break statements cause


control to break out of the switch and continue with
the first statement following the switch. The break
statements are necessary because case statements
fall through. That is, without an explicit break control
will flow sequentially through subsequent case
statements.

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Javas continue statement


Continue statements : Like the break statement, Java
supports another similar statement called the continue
statement. However, unlike the break which causes
the loop to be terminated, the continue, as the name
implies, causes the loop to be continued with the next
iteration after skipping any statements in between.
The continue statement tells the compiler, SKIP THE
FOLLOWING STATEMENTS AND CONTINUE WITH THE
NEXT ITERATION.
Format:

CT010-13-Fundamentals of Software Development

continue;

Structured Programming Control Structures in Java

Javas switch statement

However, there are certain scenarios when you do


want control to proceed sequentially through case
statements. Like in the following Java code that
computes the number of days in a month :

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Javas switch statement


int month;
int numDays;
...
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
}
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Javas switch statement

Finally, you can use the default statement at the end of


the switch to handle all values that aren't explicitly
handled by one of the case statements.

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Javas switch statement


int month;
...
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Hey, that's not a valid month!");
break;
}
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Quick Review Question


The entry fee for the local art museum is calculated as
follows : children under 5 years, free; adults 65 years
and older, $1.50; all others, $2.50. Write an if
statement to print the entryFee (of type double) based
on the variable ageOfEntrant (of type int).

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Quick Review Question


The current rule for Social Security contributions is this:
7.65% of your salary, up to $67500, is taken as Social
Security (FICA) tax, then 1.45% of everything above that
is taken as Medicare tax. However, if you are selfemployed, it is 15.3% up to $67,500, then 2.9% above
that. Write a program that first asks the user whether he
or she is self-employed and then asks for the annual
salary, and calculates the FICA tax, the Medicare tax, and
the total. For example :
Are you self-employed (Enter 1 for yes, 0 for no) : 1
Your annual earnings : 91450
Your FICA tax is $10327.500
Your Medicare tax is $694.550
Your total security tax is $11022.050
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Follow Up Assignment
Work on this assignment for discussion in the next
lesson.
The Center for Disease Control in Atlanta, Georgia, has
computed various recommended values for a persons body
mass index. The body mass index is a persons weight in
kilograms divided by the square of his or her height in
meters. For men, an index of 27.8 or more is considered
high; for nonpregnant women, the cutoff is 27.3. Write an
application to read a persons gender, height and weight,
determine the bodyMassIndex, and print a message as to
whether it is high or not. Your application should convert
height from inches to meters ( 1 meter is 39.37 inches) and
weight from pounds to kilograms ( 1 kilogram is 2.20
pounds).
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Follow Up Assignment
Your output should look like this :
BODY MASS CALCULATION
Enter your gender (0 for male, 1 for female) : 1
Enter your height in inches : 69
Enter your weight in pounds : 141
Your body-mass-index is 20.90; this is not
considered high.
BODY MASS CALCULATION
Enter your gender (0 for male, 1 for female) : 1
Enter your height in inches : 61
Enter your weight in pounds : 145
Your body-mass-index is 27.47; this is considered
high.
CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Summary of Main Teaching Points


Structured Programming Control Structures
Operators and expressions
Conditional constructs
if..else constructs
nested if..else constructs
switch..case
break and continue statements

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java

Next Lesson
Structured Programming Control Structures
Looping constructs
while loop
do..while loop
for loop

CT010-13-Fundamentals of Software Development

Structured Programming Control Structures in Java