73
Lecture 10 Lecture 11 Lecture 12 Lecture 10 Algorithm Design COMP101: Introduction to Programming in JAVA Reading: Morelli Chapter 0, Chapter 2, Chapter 3, Cohoon and Davidson Chapter 1. For pseudocode see users.csc.calpoly.edu/jdalbey/SWE/pdl_std.html Russell Martin with some materials from Clare Dixon, Michele Zito, and Frans Coenen Department of Computer Science Russell.Martin(at)liv.ac.uk www2.csc.liv.ac.uk/martin/teaching/comp101 Russell Martin Algorithm Design 1 / 81

Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

  • Upload
    others

  • View
    15

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Lecture 10Algorithm Design

COMP101: Introduction to Programming in JAVA

Reading: Morelli Chapter 0, Chapter 2, Chapter 3, Cohoon andDavidson Chapter 1. For pseudocode seeusers.csc.calpoly.edu/∼jdalbey/SWE/pdl_std.html

Russell Martinwith some materials from Clare Dixon, Michele Zito, and Frans CoenenDepartment of Computer ScienceRussell.Martin(at)liv.ac.ukwww2.csc.liv.ac.uk/∼martin/teaching/comp101

Russell Martin Algorithm Design 1 / 81

Page 2: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Introduction

We are describing a process that should be used when solvinga given programming problem in Java.

First, we talked about problem decomposition into classes andtheir attributes and representing these using class diagrams.

Several questions are still unanswered:

How do we find out what computation is needed to solve aparticular problem?

How do we describe such computation?

How do we translate such descriptions into working Java code?

Russell Martin Algorithm Design 2 / 81

Page 3: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Describing Computations

The underlying assumption in our approach is that anycomputation (in fact almost any process you can think of) canbe described by a sequence of steps each being, in turn, a(simpler) computation.Thus, processes like:

Go to the local shop to buy milk

Prepare spaghetti carbonara

Search through a list of items to find a particular one

Write a book

Create the best video-game ever

Write a Java program

can all be described in terms of a sequence of steps that needto be completed to achieve the particular goal.

Russell Martin Algorithm Design 3 / 81

Page 4: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Pseudocode standards

The pseudocode language is a kind of structured English fordescribing processes.It allows the designer to focus on the logic of the processwithout being distracted by details of language syntax.

A pseudocode description needs to be complete: it shoulddescribe the entire logic of the particular process so thatimplementation becomes a mechanical task of translatingline by line into source code.The vocabulary used should be that of the problemdomain, not of Java. The pseudocode is a narrative forsomeone who knows the requirements (problem domain),and is trying to learn how the solution is organised.

Russell Martin Algorithm Design 4 / 81

Page 5: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Pseudocode conventions

Each textbook and each individual designer may have their ownpersonal style of pseudocode.

There is no universal standard.

Remember it is intended to be read by humans not computers.

The format below inspired byhttp://users.csc.calpoly.edu/∼ jdalbey/SWE/pdl_std.html

is recommended for COMP101.

Russell Martin Algorithm Design 5 / 81

Page 6: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Pseudocode conventions

There are three main ways of doing things:

sequence a process described as a sequence of stepsoccurring one after the other.“I do this, then that, then that”.

selection a process described in terms of alternatives.“If this happens, then I do this otherwise I do that.”

iteration a process described in terms of repeatedexecutions of particular actions, sometimessubject to a termination condition.“While there is still a coin in my purse, I pick one,remove it from the purse and add its value to arunning total.”

We will look at pseudocode for selection and iteration in laterweeks when we cover these issues in Java.

Russell Martin Algorithm Design 6 / 81

Page 7: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Sequence

A sequential process is indicated by writing one action afteranother, each action on a line by itself, and all actions alignedwith the same indentation. The actions are performed in thesequence (top to bottom) that they are written.

Example (non-computer)

Brush teethWash faceComb hairSmile in mirror

Example

READ height of rectangleREAD width of rectangleCOMPUTE area as height multiplied by width

Russell Martin Algorithm Design 7 / 81

Page 8: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Common Action Keywords

Several keywords are often used to indicate common input,output, and processing operations.

Input: READ , OBTAIN , GETOutput: PRINT , DISPLAY , SHOWCompute: COMPUTE , CALCULATE , DETERMINEInitialize: SETAdd one: INCREMENT

Russell Martin Algorithm Design 8 / 81

Page 9: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Object Interactions

Method invocation and message exchanging are achieved byspecifying, in plain English, the name of the object that is calledinto action, the service (method, operation, functionality) askedfrom the named object, and the data needed to carry out theparticular task.

Examples.The Swimming Pool object myPool computes the

volume of the pool.

[The current object is to] Generate an instanceof the Swimming Pool of length 5, width 4and depth 2.

Debit the Client account with ChequeAmount.

Russell Martin Algorithm Design 9 / 81

Page 10: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Method definition

Methods are defined by specifying their name, their input data,and the type of result they produce.

Example. Carrying on from one of the examples on theprevious slide, one may define

METHOD Debit AccountINPUT ChequeAmount : doubleOUTPUT None

...<pseudocode describing the processing>...

Russell Martin Algorithm Design 10 / 81

Page 11: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Golden Rules

The main purpose of using pseudocode is to describe thesystem processing at an abstract level. (!)

Rule 1 As mentioned before, one should avoid languagespecific constructs. The description should be inthe language of the problem domain.

Rule 2 If a pseudocode description is about the samelength as the corresponding actual code it isprobably too long!

A pseudocode description for a method involving essentially asingle Java statement is NOT NEEDED! Carefully chosennames for the method and its parameter list give enoughinformation about its purpose.

Russell Martin Algorithm Design 11 / 81

Page 12: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Approaches

How do we find out what computation is needed tosolve a particular programming task?

For relatively simple programming tasks (similar to those thatwe will consider), one possible approach is to perform atwo-level step-wise refinement process:

1 Decompose the task at hand in a number (usually muchless than ten) of sub-tasks.

2 Reduce the sub-tasks to Java instructions.

For complex tasks (these are not the type of problems we willconsider in this module) , usually people apply patterns. Anumber of computational problems have been studied in theliterature. Given a new programming task, it is often possible toreduce it to a combination of well-known tasks that are thensolved by applying standard well-known techniques.

Russell Martin Algorithm Design 12 / 81

Page 13: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Examples: Computing timeToFill()

ProblemWrite a program to input the length, width and depth of arectangular swimming pool of uniform depth and calculate thetime it takes to fill it. Assume the rate of flow of water into thepool is 50 litres per minute and that 1 cubic metre has acapacity of 1,000 litres of water.

SwimmingPoolUser

+ main(String[])-

SwimmingPool- RATEOFFLOW: double = 50.0

- UNITCAPACITY: double = 1000.0- length: double- width: double- depth: double

+timeToFill(): doubleRussell Martin Algorithm Design 13 / 81

Page 14: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Initial Analysis

From our verb analysis, we decided we needed the calculationof the time it takes to fill the pool.

This will be a number, resulting from some calculations. Weneed to:

1 decide who is going to have responsibility of computingthis;

2 think about its input data, return value and their types;3 define a method that will perform such computation (let’s

call it timeToFill).

Russell Martin Algorithm Design 14 / 81

Page 15: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Responsibilities

The responsibility for computing this could be either given to theSwimmingPoolUser class, in which case the method needs to getthe values for length, width, and depth from somewhere else asthe attributes in the SwimmingPool class are private to that class.

Alternatively, the operation could be assigned to theSwimmingPool class, in which case the pool sizes would beavailable to the operation and no additional input data isneeded.

This looks like part of the behaviour of SwimmingPool so we willput it there. Thus if SwimmingPool is re-used in other programs, allthe relevant methods will be provided.

Russell Martin Algorithm Design 15 / 81

Page 16: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Scenarios

1 If the swimming pool contained 1 cubic metre of water itscapacity would be 1,000 litres (this is in the problem statement!).If it takes a minute to pour 50 litres of water in the pool it wouldtake

1,00050 = 20 minutes to fill such a pool.

2 By a similar argument, if the swimming pool contained 5 cubicmetres of water it would take

5× 1,00050 = 100 minutes to fill it.

3 Generalising, if the swimming pool contained x cubic metres ofwater this number should be multiplied by the unit capacity anddivided by the rate of flow to give the correct answer. Thus, weget the answer (in minutes) from the Java expression:

x * UNITCAPACITY / RATEOFFLOW

Russell Martin Algorithm Design 16 / 81

Page 17: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Technical Issue

Conceptually, X is the volume of the pool.

Since the problem statement talks of a rectangular swimmingpool of uniform depth, we see that x is the volume of a cuboid.Instead of x lets use poolVolume

poolVolume = length * width * depth

We assume that input lengths are in metres.Russell Martin Algorithm Design 17 / 81

Page 18: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Pseudocode for timeToFill()

As length, width and depth are all doubles, given the calculationinvolved, we probably want timeToFill also to output a double.

Here’s the full specification of the required method:

METHOD timeToFillINPUTOUTPUT double

COMPUTE the volume of the pool poolVolume aslength x width x depth

RETURN (poolVolume x UNITCAPACITY) / RATEOFFLOW

Remark. It is arguable whether the given pseudocode isactually needed. In effect timeToFill is formed by a single lineof code. A pseudocode description is a bit of an overkill. (It wasgiven here for pedagogical reasons.)

Russell Martin Algorithm Design 18 / 81

Page 19: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

The main method

Assuming SwimmingPool gets the responsibility of running themethod timeToFill, the pseudocode for the main method is asfollows.

METHOD mainINPUT argsOUTPUT

LOCAL DATA lth, wth and dth (all real numbers)READ lth, wth and dth from the keyboardSET up an instance myPool of Swimming Pool setting

length=lth, width=wth and depth=dthPRINT the result of calling timeToFill() on myPool.

Russell Martin Algorithm Design 19 / 81

Page 20: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Another Example: Average Fuel Consumption

ProblemWrite a program to input the cost of fuel put in the car each dayof the (working) week, then compute the total cost and theaverage cost, and display the results of the two computations.

FuelCostUser

+ main(String[])-

FuelCost- monCost: double- tuesCost: double- wedCost: double- thursCost: double

- friCost: double+totalCost(): double

+averageCost(): double

Russell Martin Algorithm Design 20 / 81

Page 21: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Behaviours

Write a program to input the cost of fuel put in the car each day ofthe (working) week, thencompute the total cost and the average cost , and display the

results of the two computations.

We decided that we needed two methods totalCost andaverageCost.

Where are these located?–For similar reasons as withtimeToFill() we will put them in the FuelCost class.

What is their return type?–Probably double as we need toperform calculations on values that are doubles.

What pseudocode is needed for these methods?

What pseudocode is needed for the main method?

Russell Martin Algorithm Design 21 / 81

Page 22: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Summary

We have shown how to use pseudocode to write down thebehaviour of parts of the program.We have applied this to examples.

Russell Martin Algorithm Design 24 / 81

Page 23: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Lecture 11More About Methods

COMP101: Introduction to Programming in JAVA

Reading: Morelli Chapter 3, Cohoon and Davidson Chapters 2and 4

Russell Martinwith some materials from Clare Dixon, Michele Zito, and Frans CoenenDepartment of Computer ScienceRussell.Martin(at)liv.ac.ukwww2.csc.liv.ac.uk/∼martin/teaching/comp101

Russell Martin More About Methods 25 / 81

Page 24: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Overview

In this lecture we have a closer look at methods.We look at the flow of control when using methods andhow to pass information to the methods.We also discuss the scope and lifetime of identifiers.We give the implementation of the timeToFill() methodfrom the SwimmingPool class.

Russell Martin More About Methods 26 / 81

Page 25: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Methods

One of the core features of the objects in an object-orientedsystem is that they should be able to “do things”.

Methods specify the “things” that objects in a given class cando.

A method is a group of self-contained declarations andexecutable statements that performs a specific task oroperation.

As we have already seen, Java methods have the followingformat:Modifiers ReturnType Name (ParamList) { StatementList }

Russell Martin More About Methods 27 / 81

Page 26: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Methods: Example

The following was a method in the Rectangle class to calculatethe area of the rectangle.

// Method that returns the area of the rectangle.public int calculateArea() {

return length * width;}

We could add a method to the Rectangle class that prints out therectangle’s length and width.

// Print out rectangle’s length and widthpublic void printDimensions() {

System.out.println("Length: " + getLength() +" Width: " + getWidth());

System.out.println();}

Russell Martin More About Methods 28 / 81

Page 27: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Methods Control Flow

// program to demonstrate how to call a// programmer-defined methodpublic class TestMethodsControlFlow {

public static void main(String [] args) {System.out.println("Execution starts in [main] method;");display();System.out.println("back to the [main] method.");

}

// method to display a messagepublic static void display() {

System.out.println(" method [display] is then called;");}

}

>>>How does it work?<<<

Russell Martin More About Methods 29 / 81

Page 28: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Running it!

The first statement in the main method will print themessage starting Execution starts... to the screen.Then Java executes display(). It does so by jumping insidethe body of the method display at the bottom of the listingand running the method’s single statement.The sentence method [display] is then called; appearson the screen.Then execution of the method ends, and the nextstatement that is executed is the one immediately followingthe call to display. The final line back to the [main] method.

will appear on the screen.$ java TestMethodsControlFlowExecution starts in [main] method;method [display] is then called;

back to the [main] method.$

Russell Martin More About Methods 30 / 81

Page 29: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

The return Keyword

// program to demonstrate calling a method that returns// a valueimport java.util.Scanner;

public class TestMethodsWithReturnValue {

public static void main(String[] args) {System.out.println("The sum is " + sum());

}

public static int sum() {int first, second; // numbers to inputScanner input = new Scanner(System.in);System.out.print("First number? ");first = input.nextInt();System.out.print("Second number? ");second = input.nextInt();return first+second;

}}

Russell Martin More About Methods 31 / 81

Page 30: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Remarks

$ java TestMethodsWithReturnValueFirst number? 10Second number? 5The sum is 15$

The invocation to sum() in the main program creates a newexecution environment with its own memory, allocatesspace in this memory for the variables defined inside themethod, and starts executing the method’s code.The statement “return expression” is used to assign a valueto the method and return the control to the calling method.If the method type is void there is no need to use a return

statement, but one may be used to force the control backto the calling method.It is syntactically legal to have many return statementsinside a method ... but not a very good practice formaintenance as it may become difficult to trace all of them.

Russell Martin More About Methods 32 / 81

Page 31: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Parameters

Methods can receive data from the calling method in severalways.

We will comment on each of the available possibilities byreferring to the same basic piece of code.

Russell Martin More About Methods 33 / 81

Page 32: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Class or Instance Variables

// program to demonstrate calling a method that// uses class or instance variables.import java.util.Scanner;

public class TestMethodsWithClassVars {private static int first, second; // numbers to input

public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("First number? ");first = input.nextInt();System.out.print("Second number? ");second = input.nextInt();System.out.println("Sum of numbers is " + sum());System.out.println("First number is now " + first);

}

public static int sum() {first = first + second;return first;

}}

Russell Martin More About Methods 34 / 81

Page 33: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Remarks

As first and second are class variables they are accessiblethroughout the class, even in the method sum().Assigning first + second to first in sum() means the valueof first will have changed in the main method.What is output if we input 10 and 5?The static modifier was added to the declarations of firstand second otherwise Java would complain as follows:TestMethodsWithReturnValue.java:12: non-static variablefirst cannot be referenced from a static context

first = input.nextInt();ˆ

What happens if the declarations of first and second aremoved inside main?

Russell Martin More About Methods 35 / 81

Page 34: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Method Parameters

// program to demonstrate calling a method that receives its// data through a parameter list.import java.util.Scanner;

public class TestMethodsWithParameterPassing {public static int first, second; // numbers to input

public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("First number? ");first = input.nextInt();System.out.print("Second number? ");second = input.nextInt();System.out.println("Sum of numbers is " +

sum(first, second));System.out.println("First number is now " + first);

}

public static int sum( int f, int s) {f = f+s;return f;

}} Russell Martin More About Methods 38 / 81

Page 35: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Remarks

How do things work in this case?Here parameters are variables of primitive data type.The parameter list in the method call must contain thesame number of elements, in the same order and of thesame type as the parameter list in the method definition.When sum(first, second) is called from the main method thevalues of the actual parameters (first and second) areevaluated and copied as values for the formal parameters(f and s). This is known as “passing by value”.Any changes to the formal parameters (assigning f+s to f)will not affect the actual parameters, i.e. here first andsecond are not affected by the method call.Question: what would happen if the parameters werecalled first and second?

Russell Martin More About Methods 39 / 81

Page 36: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Reference Parameters I

Note that for items of data that are stored by reference (e.g.objects or arrays), the parameter mechanism has slightlydifferent effects.

In such cases the actual address of the variable is passed tothe calling method. Consequently, any change that happens tothe parameters inside the called method will remain after thecontrol is returned to the caller.

This is similar to what happens when we assign one object toanother.Rectangle rect2 = new Rectangle();Rectangle bigRect = new Rectangle(100,35);rect2 = bigRect;

Both bigRect and rect2 will refer to the same object.

Russell Martin More About Methods 41 / 81

Page 37: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Reference Parameters II

public class TestMethodsWithObjectParameters {// ---------------METHODS-------------/* Main Method */public static void main(String[] args) {

// Instantiate up bigRectRectangle bigRect = new Rectangle(100,35);

// Print out its length and widthSystem.out.println("The Big Rectangle’s dimensions");bigRect.printDimensions();

// Call changeRectangle using bigRect as parameter and print dimensionsRectangle newRect = changeRectangle(bigRect);System.out.println("After calling changeRectangle(bigRect) ");newRect.printDimensions();

Russell Martin More About Methods 42 / 81

Page 38: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Reference Parameters III

// Print out the Big Rectangle’s length and width againSystem.out.println("The Big Rectangle’s dimensions ");bigRect.printDimensions();

}

public static Rectangle changeRectangle(Rectangle theRect) {theRect.setLength(50);return theRect;

}}

This has the following output:$ java TestMethodsWithObjectParametersThe Big Rectangle’s dimensionsLength: 100 Width: 35

After calling changeRectangle(bigRect)Length: 50 Width: 35

The Big Rectangle’s dimensionsLength: 50 Width: 35$

Russell Martin More About Methods 43 / 81

Page 39: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Reference Parameters IV

bigRect

length = 100

width =35bigRect

theRect

length = 100

width =35

bigRect

newRect

length = 50

width = 35bigRect

theRect

length = 50

width =35

Russell Martin More About Methods 44 / 81

Page 40: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Scope and Lifetime of Identifiers

1 The scope of an identifier refers to the region of aprogram in which an identifier can be used.

2 An identifier with class scope is accessible throughout theentire class and anywhere in the program where an objectX of the given class is defined, prefixed by “X.” (dependenton modifiers e.g. public).

3 A block is any segment of code beginning with a { andending with a }.

4 An identifier with block or local scope is accessible from itspoint of declaration throughout the entire block in which itis defined.

Russell Martin More About Methods 45 / 81

Page 41: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Remarks

Method parameters can be thought of as having block orlocal scope. They are only accessible within the body ofthe method they refer to.Class attributes are examples of variables having classscope.Method names give another example of identifiers havingclass scope.

Russell Martin More About Methods 46 / 81

Page 42: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Scope of Identifiers

have class scope

// program to demonstrate calling a method that receives its// data through a parameter list.import java.util.Scanner;

class TestMethodsWithParameterPassing {

sum1(first, second));

private static int first, second; // numbers to input

public static void main(String[] args) { System.out.print("First number? "); first = new Scanner(System.in).nextInt(); System.out.print("Second number? "); second = new Scanner(System.in).nextInt(); System.out.println("Sum of numbers is " +

System.out.println("First number is now " + first); }

public static int sum( int f, int s) { f = f+s; return f; }

}

f, s have local orblock scope

first, second and sum()

Russell Martin More About Methods 47 / 81

Page 43: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Lifetime

The lifetime of an identifier is the period during which thevalue of the identifier exists in the computer memory.

identifiers with block scope only exist during the executionof the particular block.When an object goes out of scope, garbage collectiontakes place. (Garbage collection is the process ofreclaiming memory for re-use.)

Russell Martin More About Methods 48 / 81

Page 44: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Back to the Swimming Pool

Recall we had the following pseudocode for the methodtimeToFill located in the SwimmingPool class.

METHOD timeToFillINPUTOUTPUT double

COMPUTE the volume of the pool poolVolume aslength x width x depth

RETURN (poolVolume x UNITCAPACITY) / RATEOFFLOW

Russell Martin More About Methods 49 / 81

Page 45: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Implementation of the method TimeToFill()

/*** Compute the pool’s volume as the result of

* volume x UNITCAPACITY / RATEOFFLOW

* and return double

*/public double timeToFill( ) {

double myPool;

myPool = length * width * depth;return myPool * UNITCAPACITY / RATEOFFLOW;

}

Russell Martin More About Methods 50 / 81

Page 46: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

FuelCost: Pseudocode for totalCost and averageCost

METHOD totalCostINPUTOUTPUT double

COMPUTE the total fuel cost asmonCost + tuesCost + wedCost + thursCost + friCost

RETURN the computed value

METHOD averageCostINPUTOUTPUT double

CALL totalCost() to obtain the total cost of fuelCOMPUTE totalCost() / 5RETURN the computed value

How can we implement these?

Russell Martin More About Methods 51 / 81

Page 47: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Summary

We had a closer look at methods with respect to flow ofcontrol and parameter passing.We mentioned scope of lifetime of identifiers.We gave the implementation of the timeToFill() methodfrom the SwimmingPool class.

Russell Martin More About Methods 53 / 81

Page 48: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Lecture 12Arithmetic and the Math Class

COMP101: Introduction to Programming in JAVA

Morelli chapter 5, Cohoon and Davidson Chapter 2

Russell Martinwith some materials from Clare Dixon, Michele Zito, and Frans CoenenDepartment of Computer ScienceRussell.Martin(at)liv.ac.ukwww2.csc.liv.ac.uk/∼martin/teaching/comp101

Russell Martin Arithmetic and the Math Class 54 / 81

Page 49: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Overview

We introduce some of the features of the Math Class.We consider the analysis and design, implementation andtesting of a program to calculate area and circumference ofa circle given its radius.We discuss arithmetic testing with respect to this program.

Russell Martin Arithmetic and the Math Class 55 / 81

Page 50: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Expressions

Java supports the standard binary algebraic operators “+”, “-”,“×” and “/” (plus the remainder operator).

Recall that Java expressions may look different from theiralgebraic counterpart:

Operator Java Algebra+ x+2 x + 2- m-2 m − 2× m * 2 2m or 2 × m/ x / y x ÷ y or x

yremainder x % y x mod y

Russell Martin Arithmetic and the Math Class 56 / 81

Page 51: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Division and Remainder

Recall when applied to two integers / uses integer division.The result is the integer part of the usual division result.In Java 11/2 evaluates to 5, 6/2 evaluates to 3 as does 7/2.x % y gives the remainder after dividing x by y.In Java 11 % 2 evaluates to 1, 6 % 2 evaluates to 0, and7 % 2 evaluates to 1.

What is the result of 12/6 and 13/6?

What is the result of 12 % 6 and 13 % 6?

Russell Martin Arithmetic and the Math Class 57 / 81

Page 52: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Abbreviations: The Increment Operators

Java provides a number of unary operators that are used toincrement or decrement an integer variable. So k++ (or, resp.k--) has the effect of adding (resp. subtracting) one to (from)the variable k and assigning the resulting value to k.

Both ++k and k++ (or --k and k--) are valid incrementexpressions, but with different meanings: here’s the explanationin the case of positive increment,

The expression j = ++k corresponds to an increment of kand then the assignment of the resulting value to j. On theother hand in j = k++ the initial value of k is assigned tovariable j first and then k is increased.

Be careful when using these.

Russell Martin Arithmetic and the Math Class 58 / 81

Page 53: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Other Shortcut Operators

Similarly, Java supplies a number of “shortcut” assignmentoperators. Their format and interpretation is given in thefollowing table:

concise form equivalent verbose expressiona += b a = a + b

a -= b a = a - b

a *= b a = a * b

a /= b a = a / b

a %= b a = a % b

Note that expressions such as a =* b are not allowed.

Russell Martin Arithmetic and the Math Class 60 / 81

Page 54: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Operator Precedence

In the next table the operators we have seen so far arelisted according to precedence order, the closer to the topof the table, the higher its precedence.Operators with higher precedence are evaluated beforeoperators with lower precedence.Operators on the same line have equal precedence.When operators of equal precedence appear in the sameexpression all binary operators, except for the assignmentoperators, are evaluated from left to right; assignmentoperators are evaluated right to left.

Russell Martin Arithmetic and the Math Class 61 / 81

Page 55: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Operator Precedence

Operators Precedencepostfix expr++ expr--

unary ++expr --expr

multiplicative * / %

additive + -

assignment = += -= *= /= %=

Thus result = 3 * 8 + 2 will evaluate to the same asresult = ((3 * 8) + 2).

To ensure clarity and prevent errors, use parentheses.

Russell Martin Arithmetic and the Math Class 62 / 81

Page 56: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Dividing by Zero

When programming, always take care to avoid dividing by zero.In JavaSystem.out.println("5 /0 " + 5/ 0);

will result in the following run-time error.Exception in thread "main" java.lang.ArithmeticException: / by zeroat TestNaN.main(TestNaN.java:41)

System.out.println("5.0 / 0.0 " + 5.0 / 0.0);System.out.println("0.0 / 0.0 " + 0.0 / 0.0);

will result in5.0 / 0.0 Infinity0.0 / 0.0 NaN

NaN is short for is “not a number”.

Russell Martin Arithmetic and the Math Class 63 / 81

Page 57: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

The Math class

More advanced mathematical computations can be achievedusing operations defined in the Math class.

This class is contained in the java.lang package, includedimplicitly in all Java programs (no explicit import needed!).

The class Math contains methods for performing basic numericoperations such as the elementary exponential, logarithm,square root, and trigonometric functions.

The Math class cannot be instantiated and all its methods arestatic class methods. Hence, they are invoked through theclass name e.g. Math.round(34.2) to call the method round.For more details, seedocs.oracle.com/javase/8/docs/api/java/lang/Math.html

Russell Martin Arithmetic and the Math Class 64 / 81

Page 58: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Approximation Functions

double ceil(double a)

Returns the smallest double value that is greater thanor equal to the argument and is equal to a mathemat-ical integer. E.g. Math.ceil(10.2) returns 11.0

double floor(double a)

Returns the greatest double value that is less than orequal to the argument and is equal to a mathematicalinteger. E.g. Math.floor(10.2) returns 10.0

long round(double a)

(int) Returns the long integer closest to its argument. E.g.Math.round(10.2) returns 10

double rint(double a)

Returns the double value that is closest in value to theargument and is equal to a mathematical integer. E.g.Math.rint(10.2) returns 10.0

Russell Martin Arithmetic and the Math Class 65 / 81

Page 59: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Abs, Max, Min

double abs(double a)

It returns the absolute value of its input.E.g. Math.abs(-43.433) returns 43.433 andMath.abs(743.97) returns 743.97.

double max(double a, double b)

Returns the greater of a and b.E.g. Math.max(543.2,532.0) returns 543.2.

double min(double a, double b)

Returns the smaller of a and b.E.g. Math.min(543.2,532.0) returns 532.0.

Note abs, max, min also have versions for int, long and float

which take and return parameters of the appropriate types.

Russell Martin Arithmetic and the Math Class 67 / 81

Page 60: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Powers, Square Roots etc

double pow(double a, double b)

The expression Math.pow(a,b) computes and returnsthe value ab (as a double).

double sqrt(double a)

Returns the square root of its argument.E.g. Math.sqrt(25.0) returns 5.0

double cbrt(double a)

Returns the cube root of its argument.E.g. Math.cbrt(8.0) returns 2.0

Russell Martin Arithmetic and the Math Class 68 / 81

Page 61: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Trigonometric functionsdouble sin(double a)

Returns the trigonometric sine of its argument (con-sidered as an angle measured in radians).

double cos(double a)

Returns the trigonometric cosine of its argument(considered as an angle measured in radians).

double tan(double a)

Returns the trigonometric tangent of its argument(considered as an angle measured in radians).

double toDegrees(double angrad)

Converts an angle measured in radians to an approx-imately equivalent angle measured in degrees.

double toRadians(double angdeg)

Converts an angle measured in degrees to an approx-imately equivalent angle measured in radians.

Russell Martin Arithmetic and the Math Class 69 / 81

Page 62: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

More About the Math class

Many other trigonometric functions, e.g. the inverse functionsasin, acos, and atan are also provided.

The following useful numbers are denoted by the constants inthe Math class:

e = 2.718281828459045 . . . is Math.E; andπ = 3.141592653589793 . . . is Math.PI.

This is only a very short review of the Math class. We

did not cover all its methods andeven when we did cover a method, we only provided a veryshort description of its behaviour.

For more details read the full description available from

docs.oracle.com/javase/8/docs/api/java/lang/Math.html

Russell Martin Arithmetic and the Math Class 70 / 81

Page 63: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Example: Circle Calculation

ProblemWrite a program that calculates and outputs the circumferenceand area of a circle given its radius.

radius

Hints:assume that the radius is input by the user as a double;the area of a circle = π × radius2;Circumference = π × diameter = 2 × π × radius;Use the constant PI from the Math class.

Russell Martin Arithmetic and the Math Class 71 / 81

Page 64: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Class Analysis

Very little analysis needed. The statement talks of a Circle (aclass) which has a radius (an attribute).

The system is supposed to calculate the circumference and thearea of the circle. The use of the word “calculate” should leadus to believe that we will need to define methods for doing this.

We assume that Circle does the relevant calculations, and wehave a CircleUser class that allows the input of thecircumference, instantiates Circle, and displays the results ofthe calculations.

A possible class diagram is on the next slide.

Russell Martin Arithmetic and the Math Class 72 / 81

Page 65: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Class Diagram

CircleUser

+ main(String[])-

Circle- radius: double

+circumference(): double+area(): double

Note that we are assigning the responsibility of computingcircumference and area of the circle to the Circle class.

Russell Martin Arithmetic and the Math Class 73 / 81

Page 66: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Processing

The main method has the usual simple task of setting up allrelevant variables, then calling the area and circumferencemethods, and finally displaying the result of the computation.

METHOD mainINPUT argsOUTPUT

LOCAL DATA radREAD rad from the keyboardSET up an instance myCircle of Circle using rad as

radius of the structurePRINT the result of calculating the circumference

and area of myCircle

Russell Martin Arithmetic and the Math Class 74 / 81

Page 67: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Active Behaviours

The class Circle is responsible for computing the circumferenceand the area of the circle

Recall that the circumference of a circle having radius r is2× π × r , whereas the area of the circle is πr2.

We will not need to write any pseudocode for this.

When this will become Java code, we may use the constantMath.PI to get an (approximate) value for π = 3.141592..., andwe may use Math.pow to compute r2 needed in the formula forthe area of the circle, or we could just use the expressionradius * radius.

Russell Martin Arithmetic and the Math Class 75 / 81

Page 68: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

The Circle Class

/*** Circle.java - michele

* Fri Oct 19 2007 11:36:59

* Edited by Clare Dixon June 2010

**/public class Circle {

// attributesprivate double radius;// constructorspublic Circle(double r) {

radius = r;}// calculates the circumference of a circle given radiuspublic double circumference() {

return 2*Math.PI*radius;}// calculates the area of a circle given radiuspublic double area() {

return Math.PI*radius*radius;}

}

Russell Martin Arithmetic and the Math Class 76 / 81

Page 69: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

The CircleUser Class

/*** CircleUser.java - michele

* Fri Oct 19 2007 11:35:59

* Edited by Clare Dixon June 2010

**/import java.util.Scanner;

public class CircleUser {public static void main(String [] args) {

Circle myCircle;Scanner input = new Scanner(System.in);double rad;System.out.print("What’s the circle radius? ");rad = input.nextDouble();myCircle = new Circle(rad);System.out.println("Circumference = " +

myCircle.circumference());System.out.println("Area = " + myCircle.area());

}}

Russell Martin Arithmetic and the Math Class 77 / 81

Page 70: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Arithmetic Testing

Given an arithmetic statement, it is always a good idea totest the effect that negative, positive and zero samplevalues will have on the outcome.In this case, there is only one numeric input, we shouldtherefore test, negative and positive inputs as well as zero.If there is more than one input, we should test everypossible combination of positive, negative and zero input.Thus, if we have two inputs we would have 3× 3 possiblecombinations, with three inputs 3× 3× 3 possiblecombinations (and so on).This form of testing is known as arithmetic testing.

Russell Martin Arithmetic and the Math Class 78 / 81

Page 71: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Arithmetic Testing: The Circle

Test Case Expected ResultRadius Circumference Area

10.0 62.832 314.1590.0 0.000 0.000

-10.0 -62.832 314.159

Note that when we input a negative number we produce anegative circumference - this is probably not the desired result.

We should return to the requirements phase and determinewhat action we should take in the event of a negative radius.

What might this be?

However, with our current level of programming skills, we willjust have to ”live with this undesirable result”.

Russell Martin Arithmetic and the Math Class 79 / 81

Page 72: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Arithmetic Testing: Output

The following is the actual output.$ java CircleUserWhat’s the circle radius? 10.0Circumference = 62.83185307179586Area = 314.1592653589793

$ java CircleUserWhat’s the circle radius? 0.0Circumference = 0.0Area = 0.0

$ java CircleUserWhat’s the circle radius? -10.0Circumference = -62.83185307179586Area = 314.1592653589793$

How could we improve on the presentation of this output?

Russell Martin Arithmetic and the Math Class 80 / 81

Page 73: Lecture 10 - cgi.csc.liv.ac.ukkjc/COURSENOTES/101/w4-print.pdf · Sequence A sequential process is indicated by writing one action after another, each action on a line by itself,

Lecture 10 Lecture 11 Lecture 12

Summary

We introduced some of the features of the Math ClassWe considered the analysis and design of a program tocalculate some values of a circle given its radius.We gave the implementation of these classes.We discussed arithmetic testing with respect to ourprogram.

Russell Martin Arithmetic and the Math Class 81 / 81