Download Andrew Jones Assignment Part B: Word doc

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
FOUNDATION DEGREE IN ICT
(UNIVERSITY OF CHESTER)
Student Number:
Andrew Jones
Module:
CO5045
Further Programming
Module Tutor:
Delivering College:
Mid Cheshire College
Assessment Number and Title: 2 – Abstract Data Types
ASSIGNMENT – PART B
Overview:



This assignment is worth 100% of the module overall and covers some or all of the
outcomes 1, 2, 3, 4, 5.
The assessment method for this module has been split into four to spread student
workload. (Assignment Part A - 9%, Assignment Part B - 26%, Assignment Part C 10%, Assignment Part D - 55%), however, the method of assessment is a single
assignment worth 100%.
Refer to Module Descriptor for further details
Due Date:
Assessor:
IV
assessor:
4.00pm (1600hrs) on Friday,
11th December 2009
Submitted:
Mark
awarded (re
MAB):
Project
You are to demonstrate your understanding of the following programming concepts.
Emphasis will be made on your use of own or other coded examples to explain
the topic.
You need to show your understanding of:
Assessment
Task 1
%
Object Orientated Programming – polymorphism.
1
Illustrate your knowledge by including annotated code examples to
demonstrate the topic.
Task 2
Abstract Data Types – Illustrate three Abstract Data Types (ADT’s) from
the following list :- arrays, linked lists, queues, heaps, trees or how a binary
tree is traversed
12
Marks for this task will be awarded for program examples with written text,
and graphical representation to explain the data type.
Task 3
Programming – demonstrate your knowledge of Java using annotated
code examples and screen prints with supporting text. You must include the
following topics:





packages and class library use, class constructors,
main class,
GUI controls,
Event driven programming (including action listeners)
Exception handling (try – catch)
Your report should be of sufficient size to show your knowledge and understanding.
If you use references or examples of code from books or internet sites they have to
be properly attributed (for example using the Harvard reference system) and in the
case of internet sites the full address should be shown.
13
Table of Contents
Object Orientated Programming ............................................................................ 5
Polymorphism................................................................................................... 5
Abstract Data Types ............................................................................................. 6
Arrays .............................................................................................................. 6
Queues ............................................................................................................ 7
Stacks .............................................................................................................. 9
Programming ..................................................................................................... 10
Packages and class library use, class constructors............................................. 10
Packages .................................................................................................... 10
Class libraries .............................................................................................. 10
Class constructors ....................................................................................... 11
Main class ...................................................................................................... 11
GUI controls ................................................................................................... 12
Event driven programming (including action listeners) ...................................... 12
Exception handling ......................................................................................... 13
Bibliography and References ............................................................................... 14
Bibliography ...................................................................................................... 14
References ..................................................................................................... 14
Polymorphism ............................................................................................. 14
Queues ....................................................................................................... 14
Stacks ........................................................................................................ 14
Packages .................................................................................................... 15
Class libraries .............................................................................................. 15
Object Orientated Programming
Polymorphism
Polymorphism is one of the core
principles in Object Orientated
Programming; two others are
Encapsulation and Inheritance.
“Poly- meaning many, from
the Greek polus meaning much; and,
morphism meaning forms, from the
Greek morphe meaning form.”
(Fowler & Fowler, 1942)
So as polymorphism applies to Java
and Object Orientated Programming
it means that an object can have
many forms. For example if we have
an interface called vehicle we can
create an abstract class called
motorVehicle which implements
vehicle with a methods called
manufacturer() and description() we
can now create subclasses of and
extend the object motorVehicle()
with subclasses such as sportsCar(),
hgv() and van(),all of which have a
method called description() which is
different for each implementation of
the subclass.
This offers the opportunity to re-use
method names in the subclasses of
an object.
Polymorphism gives us the ability,
with inheritance, to re-use the same
method signatures in subclasses of
an object. Subclasses of a class are
able to define their own unique
behaviours; and, yet share some of
the same functionality of the parent
class.
interface vehicle {
String manufacturer();
String description();
}
abstract class motorVehicle implements vehicle {
private final String manufacturer;
protected motorVehicle(String manufacturer) {
this.manufacturer = manufacturer;
}
public String manufacturer() {
return manufacturer;
}
}
class sportsCar extends motorVehicle {
public sportsCar(String manufacturer) {
super(manufacturer);
}
public String description() {
return "i'm a sports car and am very fast...";
}
}
class hgv extends motorVehicle {
public hgv(String manufacturer){
super(manufacturer);
}
public String description(){
return "i'm a lorry...";
}
}
class van extends motorVehicle {
public van(String manufacturer) {
super(manufacturer);
}
public String description() {
return "i'm typically white and driven badly...";
}
}
public static void main(String[] args) {
motorVehicle[] vehicles = {
new sportsCar("Porsche"),
new hgv("Mercedes Benz"),
new van("Ford Transit"),
};
for (motorVehicle a : vehicles) {
System.out.println(a.manufacturer() + " " +
a.description());
}
}
There are a number of ways to use polymorphism in Java, the two most common
are:

Method overloading, this is where methods with the same name signature but
either a different number of parameters or different types in the parameter
list.

Method overriding, this is where methods that are redefined within an
inherited or subclass. They have the same signature and the subclass
definition is used.
Abstract Data Types
Arrays
An array is an object that contains elements of the same data type; its size is fixed
at the time of creation. The items within an array are called elements and are
referenced using a numerical value, which starts at zero.
First Index
10
1
12
2
6
3
5
4
19
5
1352
6
99
7
18
8
13
9
165
Element at Index 5
Indicies
Last Index
0
Figure 1
In java code to create the array in Figure 1 above the code is as follows:
int[] myArray;
// declares an array of integers
myArray = new int[10];
// allocates memory for 10 integers
myArray [0] = 10; // adds the value 10 to first element of the array
myArray [1] = 12; // adds the value 12 to second element of the array
and so on until the array is fully populated.
First Index
1
0
and
as
1
this
an
2
is
array
3
a
of
4
two
arrays
5
dimensional
this
6
array
contains
7
which
strings
8
is
for
9
known
example
Element at Index [1][5]
Indicies
Last Index
0
Figure 2
Figure 2 shows a two dimensional array, or as it is more accurately described an
array of arrays, and in Java code is constructed as follows:
String [][] myArray;
// declares an array of strings
myArray = new String[10][2];
// allocates memory for 10 rows and 2 columns
myArray [0][0] = “and”; // adds the value and to first element of the array
myArray [0][1] = “as”; // adds the value as to first row second column element of the array
myArray [1][0] = “this”; // adds the value this to second row, first column element of the
array
myArray [1][1] = “an”; // adds the value an to second row second column element of the
array
and so on until the array is completely populated.
Queues
A queue, as the name suggests, is a buffer for storing data before that data is
processed. Queues typically operate on a First In First Out (FIFO) model; although
E
D
C
B
A
Tail of the Queue
F
Head of the Queue
Items are added to the Queue


there are a number of other queue
behaviours: Last In First Out (LIFO)
and priority queues – where queue
elements are ordered according to their
values.
In a FIFO queue all the elements added
to the queue are added at the end or
tail of the queue.
Queue methods exist in two forms, one
form throws an exception and the other
returns a value when the operation
fails.
Methods that throw an exception:

Add(element)
Remove()
Element()
Returns a value



Offer(element)
Poll()
Peek()
Each queue implementation must specify its’ ordering properties; whichever ordering
priority, the head of the queue is removed by utilising the calls remove() or poll().
A coded example of a queue is as follows:
Queue myQueue = new Queue(); //create a new Queue called myQueue
myQueue.add(“first item”); //add the text first item to the head of the queue
myQueue.add(“second item”); //add the text second item to the queue
myQueue.offer(“third item”); //using the method offer add the text third item to the queue
myQueue.offer(“fourth item”); //using the method offer add the text fourth item to the queue
System.out.println("element: " + queue.element()); //prints to the console the item at the
head of the queue using the method element()
System.out.println("peek: " + queue.peek()); // prints to the console the item at the head of
the queue using the method peek()
myQueue.remove(); //removes the head of the queue using the method remove()
myQueue.poll(); //removes the head of the queue using the method poll()
A stack in Java is a Last In First Out data structure. It
extends the class vector with a number of specific
methods:
1. Empty() returns true is the stack is empty
2. Peek() which examines the top of the stack
without removing it from the stack
3. Pop() removes the top elements of the stack and
returns its’ value
4. Push(element) adds the element to the top of
the stack
5. Search(element) searches for the element and
returns its’ position in the stack
Fourth element
Third element
Second element
First element
A coded example of a stack:
Elements are pushed into the stack
Stacks
Stack myStack = new Stack(); //creates a new stack called myStack
myStack.push("first element"); //adds the text first element to the stack
myStack.push("second element"); //adds the text second element to the stack
myStack.push("third element"); //adds the text second element to the stack
if (myStack.empty() == true) { //an if statement to evaluate whether the stack is empty
System.out.println("the stack is empty"); //a print out to console if the stack is empty
} //closing bracket for the if statement
System.out.println("Peek: " + myStack.peek()); //prints to console peek: plus the contents of
the tail of the stack
myStack.pop(); //removes the tail of the stack using the method pop()
System.out.println(myStack.search("first element")); //prints to the console the position in the
stack of the searched for string first element
Programming
Packages and class library use, class constructors
Figure 3
Packages
Packages are groups of related types that provide access protection and name space
management. Packages are defined by using the key word package, which is usually
the first word in the source file followed by the package to which it is associated.
Class libraries
Class libraries are common functions and reusable code that the programme uses,
typically they are imported for use, as shown in the code below:
import java.io.*; //imports all of the java input output library
import java.util.*; //imports all of the java utilities library
import java.lang.*; //imports all of the java language library
Or they can be accessed directly, as shown below:
java.lang.Math.random(); //a fully qualified reference to the function random()
The class libraries are grouped together into packages of related functions.
Class constructors
A class constructor is used to create a class blueprint for use within the programme.
A class constructor is very similar to a method constructor; it contains the name of
the class but does not return a value. The following code illustrates a class
constructor:
public class sort { //creates a public class called sort
} //closing bracket for the class constructor
Main class
All Java programmes must have a main method with the signature:
public static void main(String[] args) //a method called main which is public static and void
This main class method provides an entry point and primary control for the
programme; this is illustrated in the following code, which runs the gui interface for
the programme:
public class Main { //class constructor for the main class
public static void main(String[] args) { //a method called main which is public static and void
java.awt.EventQueue.invokeLater(new Runnable() { //java library awt event queue invoke
later new runable
public void run() { //public method run
new gui().setVisible(true); //create a new instance of gui and sets its visibility
to true
} //closing bracket for the run method
});
} //closing bracket for the class constructor
GUI controls
Figure 4
Graphical User Interface (GUI) controls are the elements used when creating an
interface for use in the programme. As shown in figure 4 on the right hand side are
the swing library options for these GUI controls they are considered as light weight
and are platform independent.
Event driven programming (including action listeners)
Event driven programming is a programme driven by events or actions performed
within the programme. The flow of the programme is held in a waiting state until an
action or more specifically an event occurs before auctioning the next set of
instructions.
private void cmdSortArrayBMIActionPerformed(java.awt.event.ActionEvent evt) { //button listener
for an action performed
sort.stringBubbleSortAscending(1); //call the method stringBubbleSortAscending from the class
sort and pass the integer value 1
txtTextArea.setText("");//set the text of txtTextArea to nothing
CreateTable.main(); //call the method main from the CreateTable class
txtTextArea.setText("Membership No\tBMI Rating\n"); //set the text of txtTextArea to
Membership No tab BMI Rating
for (int i = 0; i < Array.getLength(); i++) { //for loop based on the size of the array
txtTextArea.append( //append text to txtTextArea
Array.getStringValue(i, 0) + "\t\t" //get the string value of row i and column 0, tab tab
+ Array.getStringValue(i, 1) + "\n"); //concatenate the string value of row i and column
1, new line
} //closing bracket for the for loop
} //closing bracket for the action listener
Exception handling
An exception is an interruption to the normal operation of a programme. When an
exception occurs it dislocates the regular flow of instructions. In Java the exception
handling system is called try/catch. Where the code to run is encapsulated within the
try statement, i.e. try and run this code and the exceptions are handled by the catch
statement.
The code below shows a try catch statement for handling a number format
exception:
/**check to validate that height is entered as a numeric value
* using a try catch statement. Set error flags and then if error set the focus
* to the height text box
*/
try
//try statement
{
//opening bracket for try statement
height = Float.parseFloat(txtHEIGHT.getText());
//asign the variable height from the text box txtHeight value as a
float
errorHEIGHT = false;
}
//set the error flag errorHEIGHT to flase, there has been no error
//closing bracket for try statement
catch (NumberFormatException n)
numeric value
{
//catch number format exception aplha characters entered instead of
//openning bracket of the catch statement
JOptionPane.showMessageDialog(
this,
//show message dialog box
//using this, the dialog box
"You must enter a valid number for height in cm", //set the message text of the dialog box
"Invalid Input",
JOptionPane.ERROR_MESSAGE);
}
//set the title of the dialog box
//invoke the dialog box
txtHEIGHT.requestFocus(true);
//set the focus to txtHEIGHT text box
txtHEIGHT.setFocusable(true);
//grant the focus to the txtHEIGHT text box
txtHEIGHT.setText("");
//set the contents of the txtHEIGHT box to nothing
errorHEIGHT = true;
//set the error flag errorHEIGHT to true, there has been an error
//closing bracket for the catch statement
Bibliography and References
Bibliography
Fowler, H., & Fowler, F. G. (1942). The Concise Oxford English Dictionary (fourth
ed.). Oxford: Oxford University Press.
References
Polymorphism
http://home.cogeco.ca/~ve3ll/jatutor5.htm
http://www.javaworld.com/javaworld/javatips/jw-javatip30.html
http://www.developer.com/java/article.php/991451/The-Essence-of-OOP-UsingJava-Polymorphism-and-the-Object-Class.htm
http://www.roseindia.net/software-tutorials/detail/10993
http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/oo.html
http://www.geekinterview.com/question_details/72171
http://www.java2s.com/Code/Java/Language-Basics/PolymorphisminJava.htm
http://www.artima.com/javaseminars/modules/PolymorphInt/index.html
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming#Java
http://www.tutorialspoint.com/java/java_polymorphism.htm
Queues
http://java.sun.com/docs/books/tutorial/collections/interfaces/queue.html
http://www.javadb.com/using-a-queue-or-linkedlist
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Queue.html
http://java.sun.com/docs/books/tutorial/collections/interfaces/
http://java.sun.com/docs/books/tutorial/collections/interfaces/queue.html
Stacks
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Stack.html
http://en.allexperts.com/q/Java-1046/2009/2/Stack-examples.htm
http://www.roseindia.net/java/beginners/stack-demo.shtml
http://www.wellho.net/resources/ex.php4?item=j714/outmarsh.java
http://www.java-samples.com/showtutorial.php?tutorialid=374
Packages
http://java.sun.com/docs/books/jls/second_edition/html/packages.doc.html#26639
http://java.sun.com/docs/books/tutorial/java/package/createpkgs.html
http://en.wikipedia.org/wiki/Java_package
Class libraries
http://en.wikipedia.org/wiki/Java_Class_Library