You are on page 1of 71

Lecture 13 Lecture 14 Lecture 15

Lecture 13
Using the Math Class and Creating a Test
Harness
COMP101: Introduction to Programming in JAVA

Morelli Chapter 5, Cohoon and Davidson Chapter 13

Clare Dixon Using the Math Class and Creating a Test Harness 1 / 81
Lecture 13 Lecture 14 Lecture 15

Overview

We consider a right angled triangle example which show


the use of pow and sqrt from the Math class. Recall
Math.pow(a,b) where a and b are both doubles returns the value
ab (as a double).
where a is a double returns the square root of its
Math.sqrt(a)
argument (as a double).
We show how to create a test harness - a program that
runs a number of test cases automatically.

Clare Dixon Using the Math Class and Creating a Test Harness 2 / 81
Lecture 13 Lecture 14 Lecture 15

Example Problem- Pythagoras

Requirements
Given the length of the ”opposite” (O) and ”adjacent” (A) sides
of a right angled triangle determine the ”hypotenuse” (H) using
Pythagoras‟ theorem:

H 2 = O 2 + A2

Assume the sides are to be doubles.

Clare Dixon Using the Math Class and Creating a Test Harness 3 / 81
Lecture 13 Lecture 14 Lecture 15

Analysis

This looks like we will need two classes (again) RATriangle and
RATriangleUser.

It looks like we need opposite and adjacent as attributes to store the


values of two of the edges.
It is less clear whether we need hypotenuse as an attribute also or
we should just calculate this when required (like we did with
area and circumference of the Circle class).
We will also need a method to calculate the hypotenuse. If we
store the hypotenuse as an attribute we will also need a method to
access this value.

Clare Dixon Using the Math Class and Creating a Test Harness 4 / 81
Lecture 13 Lecture 14 Lecture 15

Analysis- Class Diagram

We end up with the following class diagram.


RATriangle
- opposite: double
RATriangleUser
- adjacent: double

- hypotenuse: double
+ main(String[])
+ getHypotenuse():double
- calculateHypotenuse():double

Note we have decided to make the calculateHypotenuse()


method private. Why?
Where is a good place to call calculateHypotenuse()?

Clare Dixon Using the Math Class and Creating a Test Harness 5 / 81
Lecture 13 Lecture 14 Lecture 15

Pseudocode for calculateHypotenuse

METHOD calculateHypotenuse
INPUT
OUTPUT double
COMPUTE the length of the hypotenuse as
the square root of (oppositeˆ2 + adjacentˆ2)
RETUR the calculated value
N

Clare Dixon Using the Math Class and Creating a Test Harness 7 / 81
Lecture 13 Lecture 14 Lecture 15

The main method

METHOD main
INPUT args
OUTPUT
LOCAL DATA oppositeSide, adjacentSide and
hypotenuseSide (all real numbers)
READ oppositeSide and adjacentSide from the keyboard
SET up an instance newRATriangle of RATriangle setting
opposite=oppositeSide and adjacent=adjacentSide
CALCULATE the value of the hypotenuse
SET hypotenuseSide to be this value
PRINT out the input values oppositeSide, adjacentSide
and hypotenuseSide

Clare Dixon Using the Math Class and Creating a Test Harness 8 / 81
Lecture 13 Lecture 14 Lecture 15

Implementation: RATriangle Class

// TRIANGLE
// Frans Coenen March 1999
// Revised by Clare Dixon June 2010

public class RATriangle {


// ---------------------- FIELDS ---------------------
private double opposite; private
double adjacent; private double
hypotenuse;
// ------------------ CONSTRUCTORS -------------------
/* Constructor */
public RATriangle(double newOpp, double newAdj) {
opposite = newOpp;
adjacent = newAdj;
hypotenuse = calculateHypotenuse();
}

Clare Dixon Using the Math Class and Creating a Test Harness 9 / 81
Lecture 13 Lecture 14 Lecture 15

Implementation: RATriangle Class(Cont.)

// --------------------- METHODS ---------------------


/* Calculate hypotenuse */

private double calculateHypotenuse() {


// Calculate hypotenuse
return Math.sqrt(Math.pow(opposite,2)+Math.pow(adjacent,2));
}

/* Return Hypotenuse */
public double getHypotenuse() {
return hypotenuse;
}
}

Clare Dixon Using the Math Class and Creating a Test Harness 10 / 81
Lecture 13 Lecture 14 Lecture 15

Implementation: RATriangleUser Class

// TRIANGLE APPLICATION CLASS


// Frans Coenen March 1999 Revised: Friday 13 may 2005
// Revised by Clare Dixon June 2010

import java.util.*;

public class RATriangleUser {


// ------------------- FIELDS ------------------------

// ------------------ METHODS ------------------------


/** Main method */
public static void main(String args[]) {
// Create Scanner class instance
Scanner input = new Scanner(System.in); RATriangle
newRATriangle;
double oppositeSide; double
adjacentSide; double
hypotenuseSide;

Clare Dixon Using the Math Class and Creating a Test Harness 11 / 81
Lecture 13 Lecture 14 Lecture 15

Implementation: RATriangleUser Class

// Input values for opposite and adjacent sides


System.out.println("Input opposite and adjacent sides of a " +
"right angled triangle");
oppositeSide = input.nextDouble();
adjacentSide = input.nextDouble();

// Call constructor with input


newRATriangle = new RATriangle(oppositeSide,adjacentSide);

// Find out what the calculated hypotenuse is.


hypotenuseSide = newRATriangle.getHypotenuse();

// Output result
System.out.println("Given: opposite = " + oppositeSide +
", adjacent = " + adjacentSide);
System.out.println("Result: hypotenuse = " + hypotenuseSide);
}
}

Clare Dixon Using the Math Class and Creating a Test Harness 12 / 81
Lecture 13 Lecture 14 Lecture 15

Data Hiding

As mentioned is usual here we have made our attributes


private.

private double opposite;


private double adjacent;
private double hypotenuse;

What problems might we encounter if we made opposite,


adjacent or hypotenuse public?

Should we allow get methods for opposite or adjacent?

Should we allow set methods for opposite, adjacent or


hypotenuse?

Clare Dixon Using the Math Class and Creating a Test Harness 13 / 81
Lecture 13 Lecture 14 Lecture 15

Testing
An easily calculated right angle has opposite and adjacent
sides 3.0 and 4.0 and hypotenuse of 5.0. This is useful for
testing.

H 2 = 3.02 + 4.02 = 9.0 + 16.0 = 25.0 H is 5.0

Arithmetic testing: We have two inputs which can be


negative, zero or positive. Thus we should test all 9 (3x3)
possible combinations.
Clearly, we should include some mechanism where by we can
prevent the user from including negative inputs, however with
our present knowledge this is not possible.
However it is important here is to ensure that the program
operates as expected (i.e. it produces the expected result for each
test case and does not cause a ”crash”).
Clare Dixon Using the Math Class and Creating a Test Harness 16 / 81
Lecture 13 Lecture 14 Lecture 15

Testing

Test Case Expected Result


opposite adjacent hypotenuse
4.0 3.0 5.0
4.0 0.0 4.0
4.0 -3.0 5.0
0.0 3.0 3.0
0.0 0.0 0.0
0.0 -3.0 3.0
-4.0 3.0 5.0
-4.0 0.0 4.0
-4.0 -3.0 5.0

Clare Dixon Using the Math Class and Creating a Test Harness 17 / 81
Lecture 13 Lecture 14 Lecture 15

Creating a Test Harness

From the above 9 test cases are required to test the


RATriangle class.
We can reduce the testing effort by writing a test harness.
The aim is to provide methods, in the test harness, to test
each of our test cases.
Some suitable Java code to do this is given on the next
slide.
The code comprises three methods, a main method and
two others: includeAdjValue and makeCalcAndOutput.

Clare Dixon Using the Math Class and Creating a Test Harness 18 / 81
Lecture 13 Lecture 14 Lecture 15

Test Harness Code

// TRIANGLE TEST CLASS


// Frans Coenen March 1999
// Revised by Clare Dixon June 2010

public class RATriangleTest {


// ------------------ METHODS ------------------------
/* Main method */
public static void main(String[] args) {
includeAdjValue(4.0);
includeAdjValue(0.0);
includeAdjValue(-4.0);
}
/* Add adjacent value */
public static void includeAdjValue(double opposite) {
makeCalcAndOutput(opposite,3.0);
makeCalcAndOutput(opposite,0.0);
makeCalcAndOutput(opposite,-3.0);
}

Clare Dixon Using the Math Class and Creating a Test Harness 19 / 81
Lecture 13 Lecture 14 Lecture 15

Test Harness Code(Cont.)

/* Make calculation and output */


public static void makeCalcAndOutput(double oppositeSide,
double adjacentSide) {
// Call constructor with input
RATriangle newRATriangle = new
RATriangle(oppositeSide,adjacentSide);
// Output result
System.out.println("Given: opposite = " + oppositeSide +
", adjacent = " + adjacentSide);
double hypotenuseSide = newRATriangle.getHypotenuse();
System.out.println("Result: hypotenuse = " + hypotenuseSide);
}
}

Clare Dixon Using the Math Class and Creating a Test Harness 20 / 81
Lecture 13 Lecture 14 Lecture 15

Output

$ java RATriangleTest
Given: opposite = 4.0, adjacent = 3.0
Result: hypotenuse = 5.0
Given: opposite = 4.0, adjacent = 0.0
Result: hypotenuse = 4.0
Given: opposite = 4.0, adjacent = -3.0
Result: hypotenuse = 5.0
Given: opposite = 0.0, adjacent = 3.0
Result: hypotenuse = 3.0
Given: opposite = 0.0, adjacent = 0.0
Result: hypotenuse = 0.0
Given: opposite = 0.0, adjacent = -3.0
Result: hypotenuse = 3.0
Given: opposite = -4.0, adjacent = 3.0
Result: hypotenuse = 5.0
-4.0, adjacent = 0.0
Given: opposite =
= 4.0
Result: hypotenuse
-4.0, adjacent = -3.0
Given: opposite =
= 5.0
Result: hypotenuse
$

Clare Dixon Using the Math Class and Creating a Test Harness 21 / 81
Lecture 13 Lecture 14 Lecture 15

Printing to a Number of Decimal Places

Given the previous programme if we input 5.0 and 6.0 for


opposite
p
and adjacent sides the hypotenuse should be
(5.0)2 + (6.0)2 = 7.8102497

How do we print this out to 3 decimal places?

We could use printf instead of println to provide formatted


output.
System.out.printf("Result: hypotenuse = %.3f\n", hypotenuseSide);

This gives the following output.


Given: opposite = 5.0, adjacent = 6.0
Result: hypotenuse = 7.810

Clare Dixon Using the Math Class and Creating a Test Harness 22 / 81
Lecture 13 Lecture 14 Lecture 15

Summary

We looked at further use of the Math class calling the


methods pow and sqrt.
We considered a right angled triangle example which
required the calculation of the hypotenuse from the other
two sides.
We decided to store the hypotenuse as an attribute and
calculated it as part of the RATriangle constructor.
We considered arithmetic testing for this program.
We showed how to create a test harness - a program that
runs a number of test cases automatically.

Clare Dixon Using the Math Class and Creating a Test Harness 23 / 81
Lecture 13 Lecture 14 Lecture 15

Lecture 14
Type Conversion

COMP101: Introduction to Programming in JAVA

Morelli Chapter 5, Cohoon and Davidson Chapter 2

Clare Dixon Type Conversion 24 / 81


Lecture 13 Lecture 14 Lecture 15

Overview

It is sometimes necessary to convert a data item of one


type to another type.
For example when it is necessary to perform some
arithmetic using data items of different types (so called
mixed mode arithmetic).
Under certain circumstances type conversion can be carried
out automatically, in other cases it must be ”forced” manually
(explicitly).
We consider both of these.

Clare Dixon Type Conversion 25 / 81


Lecture 13 Lecture 14 Lecture 15

Automatic Conversion: Promotion

As we have already seen Java type conversions are performed


automatically when this can be done safely, i.e. from a narrower
data type to a wider one.
int myInt = 7;
double myDouble = myInt;

Here the value of myInt is promoted to be a double (i.e. 7.0)


before assigning it to myDouble. Similarly
int myInt = 7;
double myDouble = 10.2 + myInt;

The value of myInt is promoted to be a double before it is added


to 10.2.
Promotion or automatic conversion is like putting a small object
into a large box.

Clare Dixon Type Conversion 26 / 81


Lecture 13 Lecture 14 Lecture 15

The Failure of Automatic Conversion

Note it you try to do this the other way round you will get a
compiler error.
double myDouble = 10.7;
int myInt = myDouble;

as follows.
TestCasting.java:12: possible loss of precision
found : double
required: int
int myInt = myDouble;

We cannot automatically convert a double to an int because the


first requires more storage than the second (eg what happens with
the values after the decimal point?) so consequently information
may be lost.

Clare Dixon Type Conversion 27 / 81


Lecture 13 Lecture 14 Lecture 15

Casts

To force such a conversion (i.e. from a wider type to a narrower


one) we must carry out an explicit conversion known as a type
cast.
In Java casts have the form (Type) expression where Type is a
numeric type and expression is of a wider type eg
int myInt = (int) myDouble;

Be careful when doing this. Obviously casting a long with value


31 into an int shouldn‟t cause problems by what about casting an
int of 128 into a byte (whose largest value is 127)?

It is left to the programmer to make sure the cast can be


performed safely.

Casting is like putting a large object into a small box.

Clare Dixon Type Conversion 28 / 81


Lecture 13 Lecture 14 Lecture 15

Promotion Using Characters

Recall characters are stored using 2 bytes (unicode) and


integers using 4 bytes.
Hence we can store the value of a character as an integer as
follows.
char letter1 = ‟A‟;
System.out.println(letter1); int value1 =
letter1; System.out.println(value1);

We obtain the following output.


A
65

Java has automatically carried out this type conversion as it can be


done safely.

Clare Dixon Type Conversion 30 / 81


Lecture 13 Lecture 14 Lecture 15

Casting Using Characters

However if we try to store an integer as a character we must do


an explicit cast.
int value2 = 85;
System.out.println(value2); char letter2
= (char)value2;
System.out.println(letter2);

We obtain the following output.


85
U
Without the cast we obtain the following error.
TestChars.java:31: possible loss of precision
found : int
required: char
char letter2 = value2;
1 error ˆ

Clare Dixon Type Conversion 31 / 81


Lecture 13 Lecture 14 Lecture 15

Distinction Between Casting and Rounding

Given data of type double we can change the type so that it


becomes data of type int using a cast operation as described
above.

What happens in this case is that the decimal part of the real
number is simply omitted.

For example 99.9999 will become 99.

In such cases it might be better to round to the nearest integer


equivalent of 99.9999 (i.e. round up to 100). We cannot achieve
this using a cast, however we could use either rint, or round
(returning a double or long respectively) from the Math
class, i.e. Math.rint(99.9999) returns 100.0 or Math.round(99.9999)
returns 100.
Clare Dixon Type Conversion 32 / 81
Lecture 13 Lecture 14 Lecture 15

2-D Geographic Distance

Problem
Design and implement a Java program that determines the
geographical distance between two points located on a
geographic plane. The points are referenced using the
standard x, y Cartesian coordinate system founded on a 0 origin.
The specification requires that input should be in the
form of floats (and not standard double precision real numbers).

Clare Dixon Type Conversion 33 / 81


Lecture 13 Lecture 14 Lecture 15

Example of What is Required

y
(2,10)
10

10 −5 =5

5
9−2 = 7 (9,5)

2 9 x

In the above diagram there are two points (2,10) and (9,5).

To calculate the distance between them we need to take the


absolute value of the difference between the x coordinates and the
absolute value of the difference between the y coordinates and
then use Pythagoras‟ theorem.
Clare Dixon Type Conversion 34 / 81
Lecture 13 Lecture 14 Lecture 15

Class Diagram

Point2D RATriangle
- x coord : float - opposite: double
- y coord: float - adjacent: double

+ getX coord(): float - hypotenuse: double
+ getY coord(): float + getHypotenuse():double
+ geoDist2D(Point2D): float - calculateHypotenuse():double

GeoDist2DUser

+ main(String[])
- create2DPoint(int): Point2D

Clare Dixon Type Conversion 36 / 81


Lecture 13 Lecture 14 Lecture 15

Processing
The geoDist2D method calculates the distance between x and y
co-ordinates of the two points, uses this to create an instance of
the RATriangle which will calculate the distance between them.
Note the result must be cast back into a float.
METHO geoDist2D
D pointTwo: Point2D
INPUT float
OUTPU
CALCULAT the (absolute) distance between the x_coords
T E current Point2D and pointTwo
of the the (absolute) distance between the y_coords
CALCULAT
of the current Point2D and pointTwo
E
SET up an instance newTriangle of RATriangle using the calculated
distances
CALL getHypotenuse on newTriangle to calculate the required
distance
CONVERT to a float
RETURN this value

Clare Dixon Type Conversion 37 / 81


Lecture 13 Lecture 14 Lecture 15

Implementation: Point2D
// (2-D) COORDINATE
// Frans Coenen 1999
// Revised Clare Dixon 2011

public class Point2D {

// ---------------------- FIELDS ---------------------


private float x_coord;
private float y_coord;
// ------------------ CONSTRUCTORS -------------------
public Point2D(float newX, float newY) {
x_coord = newX;
y_coord = newY;
}
// --------------------- METHODS ---------------------
/* Get methods to access x and y co-ordinates */
public float getX_coord(){
return x_coord;
}
public float getY_coord(){
return y_coord;
}
Clare Dixon Type Conversion 38 / 81
Lecture 13 Lecture 14 Lecture 15

Implementation: Point2D (2)

// --------------------- METHODS ---------------------


/* Method to Calculate 2-D geographic distance. (Method uses method in
RATriangle class to do this). */

public float geoDist2D(Point2D pointTwo) {


float diffInX, diffInY, distance;

// Calculate differences
diffInX = Math.abs(pointTwo.getX_coord() - x_coord);
diffInY = Math.abs(pointTwo.getY_coord() - y_coord);

// Resolve "triangle" using RATriangle class methods

RATriangle newTriangle = new RATriangle(diffInX,diffInY);


distance = (float) newTriangle.getHypotenuse();

// Return result
return distance;
}
}

Clare Dixon Type Conversion 39 / 81


Lecture 13 Lecture 14 Lecture 15

Pseudocode for Input of Points

As we need to obtain input for two instances of points we


devise a method to do this.

METHO create2Dpoint
D pointNumber
INPUT Point2D
OUTPU
LOCAL DATA x_coord, y_coord
T READ x_coord and y_coord from the keyboard
SET up an instance newPoint of Point2D using
x_coord and y_coord
RETURN newPoint

Why have we bothered writing a special method for this?

Clare Dixon Type Conversion 40 / 81


Lecture 13 Lecture 14 Lecture 15

Pseudocode for Main Method

The main method has the usual task creating two Point2D
instances and then calling the geographical distance between
them and displaying the result of the computation.

METHO main
D args
INPUT
OUTPU up two instances point1 and point2 of Point2D
T CALCULATE the distance between them
SET
PRINT a message including the result calculating of
the distance

Clare Dixon Type Conversion 41 / 81


Lecture 13 Lecture 14 Lecture 15

Implementation: GeoDist2DUser

// GEOGRAPHIC 2-D DISTANCE APPLICATION


// Frans Coenen March 1999
// Revised: Thursday 12 May 2005

import java.util.*;

public class GeoDist2DUser {


// ------------------- FIELDS ------------------------
// ------------------ METHODS ------------------------
/** Main method */
public static void main(String[] args) {
// Create points 1 and 2
Point2D point1 = create2DPoint(1); Point2D
point2 = create2DPoint(2);

// Calculate distance and output


float geoDistance = point1.geoDist2D(point2); System.out.println("Geographic
distance = " + geoDistance);
}

Clare Dixon Type Conversion 42 / 81


Lecture 13 Lecture 14 Lecture 15

Implementation: GeoDist2DUser (2)


/* CREATE 2D POINT: Method to input x and y for a point, request input
and then create an instance of the
class Point2D */

private static Point2D create2DPoint(int pointNumber) {


// Create Scanner
Scanner input = new Scanner(System.in);

// Invite input
System.out.println("Input x coord for point " + pointNumber +
" (floats)");
float x_coord = input.nextFloat();
System.out.println("Input y coord for point " + pointNumber +
" (floats)");
float y_coord = input.nextFloat();
System.out.println("Point " + pointNumber + ": x = " +
x_coord + " y = " + y_coord);
// Create instance of class Point2D
Point2D newPoint = new Point2D(x_coord,y_coord);
// Return
return newPoint;
}
} Clare Dixon Type Conversion 43 / 81
Lecture 13 Lecture 14 Lecture 15

Remarks
We have calculated the distance between the points using the
following.
float geoDistance = point1.geoDist2D(point2); System.out.println("Geographic
distance = " + geoDistance);

Would it matter if we used the following instead?


float geoDistance = point2.geoDist2D(point1);
System.out.println("Geographic distance = " + geoDistance);

point1 point1
y y
(2,10) (2,10)
10 10

5−10 =−5 10 −5 =5

point2 point2
5 5
(9,5) 2−9 = −7 (9,5)
9−2 = 7

2 9 x 2 9 x

Clare Dixon Type Conversion 44 / 81


Lecture 13 Lecture 14 Lecture 15

Testing

Arithmetic testing: We have four input values which can be


negative, zero or positive. Thus there are a total of 81
(3x3x3x3) test cases to consider.

Test Case Expected Result


x1 y1 x2 y2 Distance
4.0 4.0 3.0 3.0 1.414
4.0 4.0 3.0 0.0 4.123
4.0 4.0 3.0 -3.0 7.071
.. .. .. .. ..

As we have done previously a good way to test these cases is


to write a test harness.

Clare Dixon Type Conversion 45 / 81


Lecture 13 Lecture 14 Lecture 15

Output

$ java GeoDist2DTestHarness
Given points: (4.0,4.0) and (3.0,3.0) Geographic
distance is 1.4142135

Given points: (4.0,4.0) and (3.0,0.0)


Geographic distance is 4.1231055

Given points: (4.0,4.0) and (3.0,-3.0)


Geographic distance is 7.071068

...........

Clare Dixon Type Conversion 46 / 81


Lecture 13 Lecture 14 Lecture 15

Java API

In the lecture we have developed a class Point2D.

If we look in the Java API we can see that there are already
similar classes
java.awt.Point which has two integer attributes x and y.
java.awt.Point2D.Float which has two float attributes x and
y.

java.awt.Point2D.Double which has two double attributes x


and y.

These all have methods distance with various parameters that


calculate the distance between points.

Clare Dixon Type Conversion 47 / 81


Lecture 13 Lecture 14 Lecture 15

Summary

We looked at automatic conversion of types (promotion)


and forced conversion (casting).
We considered an example which used both of these
which re-used the RATriangle class we developed in a
previous week.

Clare Dixon Type Conversion 48 / 81


Lecture 13 Lecture 14 Lecture 15

Lecture 15
Selections(If-else)

COMP101: Introduction to Programming in JAVA

Morelli chapter 3, Cohoon and Davidson Chapter 5

Clare Dixon Selections(If-else) 49 / 81


Lecture 13 Lecture 14 Lecture 15

Our Programs So Far

Until now our Java programs have included one or two classes
(plus references to pre-defined classes like String or Math).
However the methods have been simply sequences of
statements eg doing assignment or I/O.

Example. How to make bruschetta bread.


Slice the bread;
Grill the slices until brown;
Grate a garlic clove on each slice;
Garnish with a little extra-virgin olive oil;
Add half a juicy tomato on top.
No scope for variations!!

Clare Dixon Selections(If-else) 50 / 81


Lecture 13 Lecture 14 Lecture 15

Example

Prepare a “flexible” bruschetta bread.


Slice the bread;
Grill the slices until brown;
Grate a garlic clove on each slice;
IF you likeit hot
sprinkle chopped chillies on top of the bread
ELSE IF you likeit „cheesy‟
grate a little parmesan OR
some mature cheese on top of the bread;
Garnish with a little extra-virgin olive oil;
IF you have a few rocket leaves add them
on top of the bread;
Add half a juicy tomato on top.

You make a different choice and you get many different


bruschetta variants.

Clare Dixon Selections(If-else) 51 / 81


Lecture 13 Lecture 14 Lecture 15

Selection

In this lecture we show how such statements are encoded in


Java, known in general as selection statements.

A selection statement provides for selection between


alternatives.

We can identify two main types of selection construct:


if-else statements; and switch
(or case) statements.

Clare Dixon Selections(If-else) 52 / 81


Lecture 13 Lecture 14 Lecture 15

Syntax of if-else Statements

The general format of an if-else statement in Java is

if ( condition )
{ statements1 }
else <=== This part may not
{ statements2 } <=== be there

Meaning: if the stated condition is true then the first set of


statements (statements1) is executed, otherwise the second set
(statements2) is executed.
Each set of statements can consist of a single instruction
terminated by the semicolon, or a sequence of instructions
ENCLOSED IN CURLY BRACKETS.

Clare Dixon Selections(If-else) 53 / 81


Lecture 13 Lecture 14 Lecture 15

Semantics of if-else Statements

if ( condition )
if ( condition ) { statements1 }
{ statements } else
{ statements2 }

true boolean false


true boolean
condition
condition

statements1 statements2
false
statement(s)

Clare Dixon Selections(If-else) 54 / 81


Lecture 13 Lecture 14 Lecture 15

Conditions

What goes in the condition part? Any expression that evaluates


to either true or false!
Examples.
1 A comparison between two variables (“if A is greater than
B then something happens otherwise something else
happens”)
2 The check that some expression is not larger than a
certain threshold (“if the employee earns less than
100,000,000 pounds tax him at 22%”).
3 Check that input is within the desired range. (eg
disallowing a negative value for a circle radius).
In Java such conditions usually involve variables and, so called,
relational operators.
Clare Dixon Selections(If-else) 55 / 81
Lecture 13 Lecture 14 Lecture 15

Relational Operators

A relational operator is a function that takes two inputs


belonging to a primitive type and returns a “YES/NO”
(“TRUE/FALSE”) answer.

Relational operators in Java are normally placed between the


two expressions they compare.
A list of relational operators is given below
operator meaning
> greater than
< less than
== equal to
>= greater than or equal to
<= less than or equal to
!= not equal to

Clare Dixon Selections(If-else) 56 / 81


Lecture 13 Lecture 14 Lecture 15

Example Problem – Power 4

Requirements
Design and create a Java program that takes a single integer
as input. If the input is less than 50 add 10 and return the result
raised to the power of 4, otherwise simply return the input
raised to the power of 4.

(x + 10)4 if x < 50
f (x ) =
x4 otherwise

Clare Dixon Selections(If-else) 57 / 81


Lecture 13 Lecture 14 Lecture 15

Analysis

As this is such a simple program we will just use one class


Power4App. We encode the calculation as a method.

Power4App

+ main(String[])
+ power4(int): int

Clare Dixon Selections(If-else) 58 / 81


Lecture 13 Lecture 14 Lecture 15

Processing

The main method has the task of obtaining the integer input
from the keyboard, calling the power4 method to perform the
calculation and printing the result.

METHOD main
INPUT args
OUTPUT
LOCAL DATA inputInteger
READ inputInteger from the keyboard
PRINT the result of applying the power4 inputInteger method to

Clare Dixon Selections(If-else) 59 / 81


Lecture 13 Lecture 14 Lecture 15

Processing: power4 Method

The power4 method checks the value of its parameter and


adding 10 if necessary, performing the required calculation and
returning the result.

METHO power4
D inputValue
INPUT integer
OUTPU
IF inputValue < 50
T add 10 to inputValue
CALCULATE the value of inputValue raised
to the power of 4
RETURN the result

Clare Dixon Selections(If-else) 60 / 81


Lecture 13 Lecture 14 Lecture 15

Diagram of Flow of Control


We provide a flow of control diagram for the if statement.

true
inputValue
< 50

false
add 10 to inputValue

raise inputValue
to the power of 4

Clare Dixon Selections(If-else) 61 / 81


Lecture 13 Lecture 14 Lecture 15

Implementation

// POWER 4 APPLICATION
// Frans Coenen: March 1999, revised 2005
// Revised by Clare Dixon 2011

import java.util.*;
public class Power4App {
// ------------------- FIELDS ------------------------
// ------------------ METHODS ------------------------
/* Main method */
public static void main(String[] args) {
// Create Scanner class instance
Scanner input = new Scanner(System.in);
int inputInteger;
// Input
System.out.print("Input an integer: ");
inputInteger = input.nextInt();
// Output
System.out.println("Result is: " + power4(inputInteger));
}

Clare Dixon Selections(If-else) 62 / 81


Lecture 13 Lecture 14 Lecture 15

Implementation

// Method which increments its parameter by 10 if it is


// less than 50 and then raises it to the power of 4.

public static int power4(int inputValue) {


if (inputValue < 50)
inputValue = inputValue + 10;
inputValue = (int)Math.pow(inputValue,4.0);
return inputValue;
}
}

Clare Dixon Selections(If-else) 63 / 81


Lecture 13 Lecture 14 Lecture 15

Arithmetic Testing

We should derive test cases incorporating positive, negative


and zero sample values. An appropriate set of cases is given
below.

Test Case Expected Result


Input Integer Output
10 160000
0 10000
-10 0

Clare Dixon Selections(If-else) 64 / 81


Lecture 13 Lecture 14 Lecture 15

Arithmetic Testing:Output

The output we obtain is as follows.


$ java Power4App
Input an integer: 10
Result is: 160000

$ java Power4App
Input an integer: 0
Result is: 10000

$ java Power4App
Input an integer: -10
Result is: 0

Clare Dixon Selections(If-else) 65 / 81


Lecture 13 Lecture 14 Lecture 15

Path Testing
An ”if” statement should always be tested using at least two test
cases, one that causes the if statement to succeed and one that
causes it to fail.
Both ”paths” through the procedure should be tested (known as
path testing).
It is also a good idea, when using discrete data items in the
condition expression, to test at the ”cut-off” point where
appropriate, i.e. 49 and 50 in this case (in the spirit of range and
limit testing). A suitable set of test cases are given below.
Test Case Expected Result
Input Integer Output
10 160000
49 12117361
50 6250000
59 12117361

Clare Dixon Selections(If-else) 66 / 81


Lecture 13 Lecture 14 Lecture 15

Path Testing: Output

The output we obtain is as follows.


$ java Power4App
Input an integer: 10
Result is: 160000

$ java Power4App
Input an integer: 49
Result is: 12117361

$ java Power4App
Input an integer: 50
Result is: 6250000

$ java Power4App
Input an integer: 59
Result is: 12117361

Clare Dixon Selections(If-else) 67 / 81


Lecture 13 Lecture 14 Lecture 15

Black and White Box Testing

Techniques such as arithmetic testing are generally


regarded as Black Box Testing techniques.
That is the software to be tested is to be regarded as a
box, the internal workings of which cannot be seen, into
which we feed input data which outputs data as a result.
Thus black box test cases are only concerned with input and
output and not the nature of the transformation(s) that causes
the first to become the second.
The opposite of black box testing is white box (or glass
box) testing.
White box testing is concerned with the inner workings of
software systems.
Path testing is an example of a white box testing technique.

Clare Dixon Selections(If-else) 68 / 81


Lecture 13 Lecture 14 Lecture 15

Example Problem – Integer Classification

Requirements
Design and create a Java program that takes a single integer as
input and classifies it as positive, negative or zero.

Analysis and Design


Lets think about this together.

Clare Dixon Selections(If-else) 69 / 81


Lecture 13 Lecture 14 Lecture 15

Implementation

/**
* Author: Clare Dixon July 2010,
* Updated 2012
* Example of using if statements and relational operators
*/
import java.util.Scanner;

public class IntegerClassification {


// ---------------METHODS-------------
/* Main Method */
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int value;
System.out.print("Please provide an integer value: ");
value = input.nextInt(); //read the value from the keyboard
System.out.println(classify(value)); //prints out result strin
}

Clare Dixon Selections(If-else) 74 / 81


Lecture 13 Lecture 14 Lecture 15

Implementation

// Method that returns a String depending on the value of the inpu


public static String classify (int val) {
String resultPhrase = "Undefined value";
if (val < 0)
resultPhrase= "Your number is negative";
else {
if (val == 0)
resultPhrase= "Your number is zero";
else {
if (val > 0)
resultPhrase= "Your number is positive";
}
}
return resultPhrase;
}
}

Clare Dixon Selections(If-else) 75 / 81


Lecture 13 Lecture 14 Lecture 15

Testing

For both path testing and arithmetic testing we should derive


test cases incorporating positive, negative and zero sample
values. An appropriate set of cases is given below.

Test Case Expected Result


Input Integer
10 positive
1 positive
0 zero
-1 negative
-10 negative

Clare Dixon Selections(If-else) 76 / 81


Lecture 13 Lecture 14 Lecture 15

Output

$ java IntegerClassification
Please provide an integer value: 10
Your number is positive

$ java IntegerClassification
Please provide an integer value: 1
Your number is positive

$ java IntegerClassification
Please provide an integer value: 0
Your number is zero

$ java IntegerClassification
Please provide an integer value: -1
Your number is negative

$ java IntegerClassification
Please provide an integer value: -10
Your number is negative

Clare Dixon Selections(If-else) 77 / 81


Lecture 13 Lecture 14 Lecture 15

Common Errors with If-Statements

The following will result in syntax errors. What is wrong?


if x < 7
System.out.println(„„Less than seven‟‟);

if (x < 7)
x = x + 10

if (x = 7)
System.out.println(„„Equal to seven‟‟);

if (x > 7)
„„Greater than seven‟‟;

Clare Dixon Selections(If-else) 78 / 81


Lecture 13 Lecture 14 Lecture 15

Common Errors with If-Statements

The following won‟t cause syntax errors but may not provide the
expected results.

.....
int x = input.nextInt(); //read the value from the keyboard
if (x > 7)
System.out.println(„„The value of x‟‟);
System.out.println(„„is greater than seven‟‟);
....

Clare Dixon Selections(If-else) 79 / 81


Lecture 13 Lecture 14 Lecture 15

Summary

We introduced the Java syntax for if-statements


We looked at the conditions used in if-statements and
provided relational operators.
We showed the usage in some example programs.
We discussed the need for path testing.
We considered some common errors when using
if-statements.

Clare Dixon Selections(If-else) 81 / 81

You might also like