Using The Math Class and Creating A Test Harness: COMP101: Introduction To Programming in JAVA
Using The Math Class and Creating A Test Harness: COMP101: Introduction To Programming in JAVA
Lecture 13
Using the Math Class and Creating a Test
Harness
COMP101: Introduction to Programming in JAVA
Clare Dixon Using the Math Class and Creating a Test Harness 1 / 81
Lecture 13 Lecture 14 Lecture 15
Overview
Clare Dixon Using the Math Class and Creating a Test Harness 2 / 81
Lecture 13 Lecture 14 Lecture 15
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
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.
Clare Dixon Using the Math Class and Creating a Test Harness 4 / 81
Lecture 13 Lecture 14 Lecture 15
Clare Dixon Using the Math Class and Creating a Test Harness 5 / 81
Lecture 13 Lecture 14 Lecture 15
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
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
// TRIANGLE
// Frans Coenen March 1999
// Revised by Clare Dixon June 2010
Clare Dixon Using the Math Class and Creating a Test Harness 9 / 81
Lecture 13 Lecture 14 Lecture 15
/* 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
import java.util.*;
Clare Dixon Using the Math Class and Creating a Test Harness 11 / 81
Lecture 13 Lecture 14 Lecture 15
// 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
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.
Testing
Clare Dixon Using the Math Class and Creating a Test Harness 17 / 81
Lecture 13 Lecture 14 Lecture 15
Clare Dixon Using the Math Class and Creating a Test Harness 18 / 81
Lecture 13 Lecture 14 Lecture 15
Clare Dixon Using the Math Class and Creating a Test Harness 19 / 81
Lecture 13 Lecture 14 Lecture 15
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
Clare Dixon Using the Math Class and Creating a Test Harness 22 / 81
Lecture 13 Lecture 14 Lecture 15
Summary
Clare Dixon Using the Math Class and Creating a Test Harness 23 / 81
Lecture 13 Lecture 14 Lecture 15
Lecture 14
Type Conversion
Overview
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;
Casts
What happens in this case is that the decimal part of the real
number is simply omitted.
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).
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).
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
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
Implementation: Point2D
// (2-D) COORDINATE
// Frans Coenen 1999
// Revised Clare Dixon 2011
// Calculate differences
diffInX = Math.abs(pointTwo.getX_coord() - x_coord);
diffInY = Math.abs(pointTwo.getY_coord() - y_coord);
// Return result
return distance;
}
}
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
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
Implementation: GeoDist2DUser
import java.util.*;
// 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);
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
Testing
Output
$ java GeoDist2DTestHarness
Given points: (4.0,4.0) and (3.0,3.0) Geographic
distance is 1.4142135
...........
Java API
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.
Summary
Lecture 15
Selections(If-else)
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
Selection
if ( condition )
{ statements1 }
else <=== This part may not
{ statements2 } <=== be there
if ( condition )
if ( condition ) { statements1 }
{ statements } else
{ statements2 }
statements1 statements2
false
statement(s)
Conditions
Relational Operators
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
Analysis
Power4App
+ main(String[])
+ power4(int): int
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
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
true
inputValue
< 50
false
add 10 to inputValue
raise inputValue
to the power of 4
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));
}
Implementation
Arithmetic Testing
Arithmetic Testing:Output
$ java Power4App
Input an integer: 0
Result is: 10000
$ java Power4App
Input an integer: -10
Result is: 0
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
$ 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
Requirements
Design and create a Java program that takes a single integer as
input and classifies it as positive, negative or zero.
Implementation
/**
* Author: Clare Dixon July 2010,
* Updated 2012
* Example of using if statements and relational operators
*/
import java.util.Scanner;
Implementation
Testing
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
if (x < 7)
x = x + 10
if (x = 7)
System.out.println(„„Equal to seven‟‟);
if (x > 7)
„„Greater than seven‟‟;
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‟‟);
....
Summary