Вы находитесь на странице: 1из 75

# ASSIGNMENT FRONT SHEET <No.

1>
Qualification

Development

title

## Unit 34: Data Structures and Algorithms

Assignment due

16-08-2016

Learners name

Assignment submitted

27-09-2016

Assessor name

## TRAN PHUOC SINH

Learner declaration:
I certify that the work submitted for this assignment is my own and research sources are fully acknowledged.
Learner signature

Date

27-09-2016

P1.
1

P1.
2

P1.
3

P2.
1

P2.
2

P2.
3

M1 M2

M3

D1

D2

D3

Assignment title

## Evaluate, Design, and Implement Data Structures and Algorithms

In this assignment, you will have opportunities to provide evidence against the following criteria.
Indicate the page numbers where the evidence can be found.

Assessment criteria

Expected evidence

no.

Assessors Feedback

## 1.1 produce design

specification for data
structures explaining
the valid operations
that can be carried out
on the structures

## 1.2 explain the

operation and
performance of sorting
and search algorithms

## Describe the data

structure(s) used and their
operations and their
relationships using
Flowchart, DFD, Class
Diagram, and Pseudo code
or any relevant
tools/diagrams to describe
the working mechanisms
of the operations
Explain and do some
- Linear search
- Binary search

1.1

1.2

## Explain and do some

exercises bout sorting:
- Selection sort
- Bubble sort
- Insertion sort
- Shell sort
- Quick sort
- Merge sort
- Heap sort

## 1.3 explain the

operation of recursive
algorithms and identify
situations when
recursion is used

## Define recursion, Tail

recursion, Non-tail
recursion, give some
examples of applications

1.3

## LO2. Be able to implement data structures and algorithms

2.1 implement data
structures in an
executable
programming language
in the context of welldefined problems

## Implement one case study

that student designed in
LO1.

2.1

## Submit code with

2.2 implement
opportunities for error
handling and reporting

## 2.3 test results to

enable comparison
with expected results.

Explain bout
where/why/how did you
apply error handling and

Test cases
Test log and evidence

Assessment criteria

Expected Evidence

2.2

2.3

Feedback
(note on Merit/Distinction if applicable)

## Merit descriptor No. (M1)

Merit descriptor No. (M2)
Merit descriptor No. (M3)
4

## Distinction descriptor No.

(D1)
Distinction descriptor No.
(D2)
Distinction descriptor No.
(D3)
Summative feedback

Assessors
Signature

Date

1.1 produce design specification for data structures explaining the valid
operations that can be carried out on the structures
Data structures used in this case are Singly Linked List, Linked implementation
of a Stack, Linked implementation of a Queue

Singly Linked List: A singly linked list is a list whose node includes two
datafields: info and next. The info field is used to store information, and this is
important to the user. The next field is used to link to its successor in this
sequence. The following image depicts a simple integer linked list.
12

15

10

Tail

Stack:
o A stackis a linear data structure that can be accessed only at one of its
ends for storing and retrieving data
o A stackis a Last In, First Out (LIFO) data structure
o Anything added to the stack goes on the top of the stack
o Anything removed from the stack is taken from the top of the stack
o Things are removed in the reverse order from that in which they were
inserted
Queue:
o A queueis a waiting line that grows by adding elements to its end and
shrinks by taking elements from its front
o A queue is a structure in which both ends are used: One for adding
new elements One for removing them
o A queue is an FIFOstructure: First In/First Out

In SMS, I use these data structures because its simple and suitable for

## Insertions and Deletions can be done easily.

It does not need movement of elements for insertion and deletion.
It space is not wasted as we can get space according to our requirements.
Its size is not fixed.
It can be extended or reduced according to requirements.
6

## Elements may or may not be stored in consecutive memory available,even

then we can store the data in computer.

## 1.2: Class diagram of SMS

DFD: This DFD shows how the system works, when customers order product, the
manager will check that product is available or not, if available the manager will
deliver that product to the customers and the customers also checkout that bill at
the same time to system. On the orther hand, the admin will have to maintain this
system regularly
ORDER
PRODDUCT

MANAGER

CUSTOMERS

DELIVER
PRODDUCT
AVAILABLE
PRODDUCT

CHECKOUT

CHECK
PRODDUCT

## Manager will have to do:

Input order, check if
those
products
available or not
Deliver products to
customers
Update order to the
system

SMS

MAINTAIN
SYSTEM

Customers:
Order product
Checkout
to
the
system
Get product after
order

Update system
Maintain
when
having errors

8

START

QUANTITY, PRICE

FALSE
VALIDATE INPUT

TRUE
FALSE

END

## Function insert new product to data structure:

Input: P001, Jeans,20,200,0
Output: new product inserted
Process:
BEGIN
Input product code, product name, quantity, price
If validate input(check if product code existed, product
name is not null, quantity and price must be well formed)
available then
Insert new product to data structure(Ex: P001,
Jeans,20,200,0)
Else input again or exit program
END

## Delete product existed in data structure:

10

START

SELECT PRODUCT
FALSE
CHECK IF PRODUCT EXISTED IN ORDER
LIST

TRUE
FALSE
DELETE PRODUCT

END

## Function delete product existed in data structure:

Input: P001, Jeans,20,200,0
Output: list products after deleting one product
Process:
BEGIN
Select product
Pseudo code delete product:
If product selected is available then
Delete product selected
Else select product again or exit programme
END

11

START
12

NOT
FOUND

CODE

FOUND
NOT
FOUND

SHOW PRODUCT

END

## Function search product existed in data structure:

Input: product code P001
Output: product found (P001,Jeans,20,200,0)
Process:
BEGIN
Pseudo code
search
product:
Input
product
code
If product existed in the data structure then
Show product found (Ex: P001, Jeans,20,200,0)
Else input pcode and search again or exit programme
END

13

START
Do
14

## change = false, current = head

While(next!=null)

## If (current code > next code)

FALSE
Swap (current,next)
change = true

## Function sort product list:

next= current.next

## Input: unsorted list products

Output: sorted list products change==true
Process:

TRUE

BEGIN

FALSE

While(change)
do

## 1.10: Bubble sort flowchart

next,
current,
is false END
Pseudo
code
sort change
product:
while next is not null
if current code bigger than next code then
swap next and current
change is true
move to next node
end if
move to next node
end while
while change is true
END

15

START

## INPUT CUSTOMER CODE,

CUSTOMER NAME, PHONE
FALSE
VALIDATE INPUT

16

TRUE
FALSE
INSERT CUSTOMER

END

## Pseudo code insert new customer:

Function insert new customer into customer list:
Input: C001, Nguyen,0203028701
Output: new customer inserted
Process:
BEGIN
Input customer code, customer name, phone number
If validate input(check if customer code existed, customer
name is not null, phone number must be well formed) available
then
Insert new customer to data structure(Ex: C001,
Nguyen,0903028701)
Else input again or exit programme
END

17

## Delete customer in data structure:

START

SELECT CUSTOMER
FALSE
CHECK IF CUSTOMER EXISTED INT ORDER LIST

TRUE
FALSE
DELETE
CUSTOMER

18

END

## Pseudo code delete customer:

Function delete customer customer list:
Input: Customer code C001
Output: Customer list after deleting
Process:
BEGIN
Select customer
If customer selected is not in order list then
Delete customer selected
Else select customer and check again or exit
program
END
1.15: Delete customer pseudo code
19

## Add new order to data structure:

START

INTPUT CUSTOMER,
PRODUCT, QUANTITY

TOTAL PRICE = QUANTITY *
PRODUCT PRICE

ORDER
20

END

## Pseudo code add new order:

Function add new order to order list:
Input: C001,P001,10
Process:
BEGIN
Input customer, product, quantity
input total = quantity * price
Order or exit program
END

21

START

## INTPUT ORDERID, PRODUCT CODE,

PRODUCT NAME, PRICE, QUANITY,
TOTAL

ORDERDETAIL

END

22

## Pseudo code add new orderdetail :

Function add new orderdetail to orderdetail list:
Input: 20140915093020,P001,Jeans,100,2,200
Jeans,100,2,200)
Process:
BEGIN
Input orderid, product code, product name, price,
quantity, total
1.19: Add new orderdetail pseudo code
1.2 Explain the operation and performance of sorting and search
algorithms
Explain and do some exercises about searching:
BEGIN
Linear search: Linear search is a very simple search algorithm. In this type of
search,LinearSearch(value,
a sequential searchlist)
is made over all items one by one. Every items is
checked and if a match founds then that particular item is returned otherwise
If the list is empty, return null;
search continues till the end of the data collection.
Here pseudo
code of Linear search recursively:
Else
If the first item of the list has the desire value then return that
item;

23

END

## 1.20: Linear search pseudo code

Apply to SMS: I use Linear search to search a product existed in
product list because it is suitable with data structure(Singly linked
list) code is show in page 45
Binary search: Binary search is a fast search algorithm with run-time
complexity of (log n). This search algorithm works on the principle of divide
and conquer. For this algorithm to work properly the data collection should be
in sorted form.
Binary search search a particular item by comparing the middle most item of
the collection. If match occurs then index of item is returned. If middle item is
greater than item then item is searched in sub-array to the right of the middle
item other wise item is search in sub-array to the left of the middle item. This
process
continues on sub-array as well until the size of subarray reduces to
BEGIN
Procedure binary_search
zero.
sorted search
array algorithm should look like this:
The pseudocode Aofbinary
N size of array
X value to be searched
Set lowerBound =1
Set upperBound=1
If upperBound<lowerBound
EXIT: x does not exists
Set midpoint = lowerBound+(upperBoundlowerBound)/2
If A[midpoint]<x
Set lowerBound = midpoint +1
If A[midpoint]>x
Set upperBound = midpoint -1
If A[midpoint]=x
EXIT: x found at location midpoint
End while
End procedure
24
END

## 1.21: Binary search pseudo code

Selection sort
o Selection sort is a simple sorting algorithm. This sorting algorithm is a
in-place comparison based algorithm in which the list is divided into two
parts, sorted part at left end and unsorted part at right end. Initially
sorted part is empty and unsorted part is entire list.
o Smallest element is selected from the unsorted array and swapped with
the leftmost element and that element becomes part of sorted array.
This process continues moving unsorted array boundary by one element
to the right.
o This algorithm is not suitable for large data sets as its average and
worst case complexity are of O(n2) where n are no. of items.
BEGIN
Pseudo code:
Procedure selection sort
List: array of items
n: size of list
for i=1 to n-1
/*set current element as minimum*/
min=i
/*check the element to be minimuon*/
for j=i+1 to n
If list[j]<list[min] then
min=j;
end if
end for
/*swap the minimum elenment with the current element*/
If indexMin!=i then
Swap list[min] and list[i]
End if
End for
25
End procedure
END

## 1.22: Selection sort pseudo code

Bubble sort
Bubble sort is a simple sorting algorithm. This sorting algorithm is
comparison based algorithm in which each pair of adjacent elements is
compared and elements are swapped if they are not in order. This algorithm is
not suitable for large data sets as its average and worst case complexity are of
O(n2) where n are no. of items.
BEGIN

Pseudo code:

## procedure bubbleSort( list : array of items )

loop = list.count;
for i = 0 to loop-1 do:
swapped = false
for j = 0 to loop-1 do:
if list[j] > list[j+1] then
/* swap them */
swap( list[j], list[j+1] )
swapped = true
end if
end for
if(not swapped) then
break
end if
end for
end procedure return list

END

26

## 1.23: Bubble sort pseudo code

Apply to SMS, I use bubble sort to sort product list because it is good for
small data and it is the fastest way in this case, code is shown in page 46,
47
Insertion sort
o This is a in-place comparison based sorting algorithm. Here, a sub-list is
maintained which is always sorted. For example, the lower part of an
array is maintained to be sorted. A element which is to be 'insert'ed in
this sorted sub-list, has to find its appropriate place and insert it there.
Hence the name insertion sort.
o The array is searched sequentially and unsorted items are moved and
BEGIN
inserted into sorted sub-list (in the same array). This algorithm is not
procedure insertionSort( A : array of items )
suitable for large data sets as its average and worst case complexity are
2
of int
(nholePosition
) where n are no. of items.
int valueToInsert
for i = 1 to length(A) inclusive do:
valueToInsert = A[i]
holePosition = i
while holePosition > 0 and A[holePosition-1] > valueToInsert do:
A[holePosition] = A[holePosition-1]
holePosition = holePosition -1
end while
A[holePosition] = valueToInsert
end for
end procedure
END

27

## 1.24: Insertion sort pseudo code

Shell sort
o Shell sort is a highly efficient sorting algorithm and is based on insertion
sort algorithm. This algorithm avoids large shifts as in case of insertion
sort if smaller value is very far right and have to move to far left.
o This algorithm uses insertion sort on widely spread elements first to sort

BEGIN

them and then sorts the less widely spaced elements. This spacing is
termed
as interval. This interval is calculated based on Knuth's formula
procedure
shellSort()
as h =h*3+1 (h is interval with initial value 1)
A : array of items
o This algorithm is quite efficient for medium sized data sets as its
while
intervaland
< A.length
/3 do:complexity are of O(n) where n are no. of items.
average
worst case

Pseudo
code:
interval
= interval * 3 + 1
end while
while interval > 0 do:
for outer = interval; outer < A.length; outer ++ do:
valueToInsert = A[outer]
inner = outer;
while inner > interval -1 && A[inner - interval] >= valueToInsert do:
A[inner] = A[inner - interval]
inner = inner - interval
end while
A[inner] = valueToInsert

28

end for
interval = (interval -1) /3;
end while
end procedure
END

## 1.25: Shell sort pseudo code

Quick sort
o Quick sort is a highly efficient sorting algorithm and is based on
partitioning of array of data into smaller arrays. A large array is
partitioned into two arrays one of which holds values smaller than
specified value say pivot based on which the partition is made and
another array holds values greater than pivot value.

29

o The quick sort partitions an array and then calls itself recursively twice
to sort the resulting two subarray. This algorithm is quite efficient for
large sized data sets as its average and worst case complexity are of
O(nlogn) where n are no. of items.

BEGIN
function partitionFunc(left, right, pivot)
leftPointer = left -1
rightPointer = right
while True do
while A[++leftPointer] < pivot do
//do-nothing

Pseudo code:

end while
while rightPointer > 0 && A[--rightPointer] > pivot do
//do-nothing
end while
if leftPointer >= rightPointer
break
else
swap leftPointer,rightPointer
end if

end while
swap leftPointer,right
return leftPointer
end function
END

30

## 1.26: QuickSort Pivot Pseudocode

BEGIN
procedure quickSort(left, right)
if right-left <= 0
return
else
pivot = A[right]
partition = partitionFunc(left, right, pivot)
quickSort(left,partition-1)
quickSort(partition+1,right)
end if
end procedure
END
1.27: Quick sort pseudo code

31

Merge sort
o Merge sort is a sorting technique based on divide and conquer
technique. With worst-case time complexity being (n log n), it is one of
the most respected algorithms.
o Merge sort first divides the array into equal halves and then combines
them in a sorted manner.
return merge( l1, l2 )

Pseudo code:

end procedure

## BEGIN procedure merge( var a as array, var b as array )

procedure
mergesort( var a as array )
var c as array
if ( n ==
1 ) return
a elements )
while
( a and
b have
var
as array
= )a[0] ... a[n/2]
if (l1a[0]
> b[0]
l2 asb[0]
array
a[n/2+1]
to =
the
end of c... a[n]
l1 =remove
mergesort(
) b
b[0] l1
from
l2else
= mergesort( l2 )
add a[0] to the end of c
remove a[0] from a
end if
end while
while ( a has elements )
add a[0] to the end of c
remove a[0] from a
end while
while ( b has elements )
add b[0] to the end of c
remove b[0] from b
end while
return c
END

end procedure

32

BEGIN
Heapsort(A as array)
BuildHeap(A)
for i = n to 1
swap(A[1], A[i])

## 1.28: Merge sort pseudo code

Heap sort
The heapsort
involves preparing the list by first turning it into a max
n =algorithm
n-1
heap. The algorithm then repeatedly swaps the first value of the list with the
last value, decreasing
Heapify(A, 1)the range of values considered in the heap operation by
one, and sifting the new first value into its position in the heap. This repeats
BuildHeap(A
as array)
until the
range of considered
values is one value in length.
Pseudo code:
n = elements_in(A)

for i = floor(n/2) to 1
Heapify(A,i)
Heapify(A as array, i as int)
left = 2i
right = 2i+1
if (left <= n) and (A[left] > A[i])
else

max = left

max = i

## if (right<=n) and (A[right] > A[max])

if (max != i)
END

swap(A[i], A[max])

max = right
Heapify(A, max)

33

BEGIN

## 1.29: Heap sort pseudo code

public static int[] sort(int[] old) {
o The fundamental principle of radix sort stems from the definition of the
stable
sorting
is stable, if it maintains the order of keys,
//
Loop sort
for every
bit in algorithm
the integers
which are equal.
for (int shift = Integer.SIZE - 1; shift > -1; shift--) {

o Radix sort iteratively orders all the strings by their n-th character in the
// The array to put the partially sorted array into
first iteration, the strings are ordered by their last character. In the second
int[]
tmp
= neware
int[old.length];
run,
the
strings
ordered in respect to their penultimate character. And
because the sort is stable, the strings, which have the same penultimate
// The number of 0s
character, are still sorted in accordance to their last characters. After n-th
intthe
j =strings
0;
run
are sorted in respect to all character positions.
// Move the
0s to the new array, and the 1s to the old one
Pseudo
code:
for (int i = 0; i < old.length; i++) {
// If there is a 1 in the bit we are testing, the number will be negative
boolean move = old[i] << shift >= 0;
// If this is the last bit, negative numbers are actually lower
if (shift == 0 ? !move : move) {
tmp[j] = old[i];
j++;

34

} else {
// It's a 1, so stick it in the old array for now
old[i - j] = old[i];
}
}
// Copy over the 1s from the old array
for (int i = j; i < tmp.length; i++) {
tmp[i] = old[i - j];
}
// And now the tmp array gets switched for another round of sorting
old = tmp;
}
return old;
}
END

35

## 1.3 explain the operation of recursive algorithms and identify

situations when recursion is used
Define recursion, Tail recursion, Non-tail recursion, give some
examples of applications
Recursion:
Wikipedia: A recursive definition or inductive definition is one that
defines something in terms of itself (that is, recursively). For it to work,
the definition in any given case must be well-founded, avoiding an
infinite regress.
A recursive definition consists of at least 2 parts:
1) A base case (anchor or the ground case) that does notcontain a
reference to its own type.
2) An inductive case that does contain a reference to its own type.
For example: Define the set of natural numbers
1. 0 N
2. If n N then (n+1) N
3. There are no other object in the set N

36

## A recursive program/algorithm is one that calls itself again. There are

three basic rules for developing recursive algorithms.
Know how to take one step.
Break each problem down into one step plus a smaller problem.
Know how and when to stop.
Tail recursion: Tail recursion is characterized by the use of only one
recursive call at the very end of a method implementation. In other words,
when the call is made, there are no statements left to be executed by the
method; the recursive call is not only the last statement but there are no
earlier recursive calls, direct or indirect. For example, the method tail() defined
as:
void tail (int i) {
if (i > 0) {
System.out.print (i +
"");

1.31: Tail
recursion
example
tail(i-1);
}}
Non tail recursion:
The recursive call is not at the very end of a method implementation
public static void reverse() throws Exception {
char ch = (char)
if(ch != '\n') {
reverse();
System.out.print(ch);
}
}

37

## Recursion occurs when a thing is defined in terms of itself or of its type.

Recursion is used in a variety of disciplines ranging from linguistics to
logic. The most common application of recursion is in mathematics and
computer science, where a function being defined is applied within its
own definition. While this apparently defines an infinite number of
instances (function values), it is often done in such a way that no loop or
infinite chain of references can occur.
The term is also used more generally to describe a process of repeating
objects in a self-similar way. For instance, when the surfaces of two
mirrors are exactly parallel with each other, the nested images that
occur are a form of infinite recursion.
Apply to SMS, I use both tail recursion and non tail-recursion
because it is is particularly useful, and easy to handle in implementations. code
is shown in page 45

## 2.1 implement data structures in an executable programming language in

the context of well-defined problems
According to the request of SMS:
public
{
Iinterface
create 4IProduct
interfaces
contain many required methods:
product Product:
Interface
contains some methods as its shown below
product displayData();
void saveDataToFile();
product insertNewProduct(String pcode,String pname, int quantity,
double price);
product searchByCode(String code);
void deleteByCode(String code);
void sortByCode();
void deleteAfterxCode(String code);
}

38

## Interface Customer: contains some abstract methods

public interface ICustomer {
customer displayData();
void saveDataToFile();
void insertNewCustomer(String code, String name, String phone);
customer searchByCode(String code);
public
IOrder {
voidinterface
deleteByCode(String
code);

order displayData();
void saveDataToFile();

## 2.2: Interface Customer

void insertNewOrder(String
String ccode,
double total);
Interface
Order: containsorderid,
some abstract
methods
void sortBycusCode();
}

39

## 2.3: Interface Order

And in order to add more than one product to order list, I also create
an Interface OrderDetail: contains some method such as
public interface IOrderDetail {
orderdetail displayData();
void saveDataToFile();
orderdetail insertNew(String orderid, String pcode, String pname, int
quantity,double price, double total);

40

## I use 4 model classes, 4 controller classes with data structure

appropriate:
Product class (Singly linked list) represent a product with its
properties
public class product implements Serializable {
public String pcode;
public class product_Controller implements IProduct {
public String pname;
public int quantity;
@Override
public int saled;
public double price;
@Override
public product next;
public product displayData() { }
}
@Override

@Override

## public product insertNewProduct(String pcode, String pname, int quantity,

some
methods
double price) { }
public product insert(product h, product pro) {

@Override
public product searchByCode(String code) {

@Override
public void deleteByCode(String code) {

@Override
public void sortByCode() {

@Override
public void deleteAfterxCode(String code) { }
public product search(product c, String code) {
private product delete(product n, String x) { }

41

@Override
try (//file is store in this directory

## FileInputStream fis = new FileInputStream("D:/DSA_product.txt");

ObjectInputStreamthis
ois =method
new ObjectInputStream(fis);)
{ from file
which is saved in the local folder directory
try {

} catch (ClassNotFoundException ex) {
}
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}

42

## 2.7: Method load data from file

Method displayData (): this method is used to show data from file after
@Override
@Override
public void saveDataToFile() {
public product displayData() {
try (//save data to file in this directory
FileOutputStream fos = new FileOutputStream("D:/DSA_product.txt");
}
ObjectOutputStream os = new ObjectOutputStream(fos);) {

## 2.8: Method display data

os.close();

Method saveDataToFile (): this method is used to save data to file in the
fos.close();
specific directory
} catch (IOException ex) {
ex.printStackTrace();
}
}

43

## Tail recursion: method search product, its used to search a product in

product list by product code
@Override

## }//call method search() with two parameters

public product search(product c, String code) {// two parameters are passed to
this method
if (c == null || c.pcode.equals(code)) {//check if c is null or c has pcode equal
to code, then return c
return c;
} else {
return search(c.next, code);//call this method recursively

}
44

## 2.10: Method search product

Non-tail recursion: method insert new product is used to insert new
product to product list
@Override

## public product insertNewProduct(String pcode, String pname, int quantity,

double price) {
product p = new product(pcode, pname, quantity, 0, price);//create new
object product
}
public product insert(product h, product pro) {
if (h == null) {//if h is null, then assign pro to h
@Override
h = pro;
public} void
{
else sortByCode()
{
boolean
h.nextchange;
= insert(h.next, pro);//next will be assigned recursively
do {
return h;
product previous = null;
}

change = false;

## while (next != null) {

In this assignment I apply bubble sort to the data structure used because
it is simple, easy
to set up and also adequated to
the
data ifstructure,
I used
if (current.pcode.compareTo(next.pcode)
> 0)
{//check
current code
>
it to sort
product
list
and
order
list.
next code
Here an example
of sorting
change
= true;product by product code with bubble sort:
if (previous != null) {//then swap the nodes
product temp = next.next;
previous.next = next;
next.next = current;
current.next = temp;

45

} else {
product temp = next.next;
next.next = current;
current.next = temp;
}
previous = next;
next = current.next;//move to next node
} else {//move to the next node
previous = current;
current = next;
next = next.next;
}
}
} while (change);
}

46

## Method deleteByCode (): this method is used to remove a product in

product
list by product code
@Override
public void deleteByCode(String code) {

## private product delete(product n, String x) {

if (n == null) {//if n is null then throw exception
throw new java.util.NoSuchElementException("cannot delete.");
} else {
if (n.pcode.equals(x)) {//if n has code equals to code then return next
return n.next;

} else {

## n.next = delete(n.next, x);

recursively to the next node
return n;

47

## 2.13: Method delete product by code

Method deleteAfterxCode (): this method is used to remove a product have
code after xcode
@Override
public void deleteAfterxCode(String code) {
publicproduct
class customer
implements
Serializable {
product =
public
String
ccode;
while
(product
!= null) {
publicif String
cname;
(product.pcode.equals(code))
{//check if product has code equals to code
public String
phone;
if (product.next
!= null) { product.next = product.next.next;//assign node
after
nextcustomer
node for next;
the current node } }
product = product.next;//move to
public
next node
} }
public customer() { }

## Customer class (Singly linked list): represents a customer with its

propertiesthis.ccode = ccode;
this.cname = cname;
this.phone = phone;
}
public customer(String ccode, String cname, String phone, customer next) {
this.ccode = ccode;
this.cname = cname;
this.phone = phone;
this.next = next;
}
}

48

## public class customer_Controller implements ICustomer {

public customer top;
@Override
@Override

## public customer displayData() { }

public customer getTop(){ }
public boolean check() { }

Customer_Controller:
implements Interfaces Customer and contains
@Override
some necessary methods
public void saveDataToFile() { }
@Override
public void insertNewCustomer(String code, String name, String phone) {}
@Override
public customer searchByCode(String code) {

@Override
public void deleteByCode(String code) {

## private customer delete(customer n, String x) {}

public customer search(customer c, String code) {}
}

49

@Override

## Method insertNewCustomer(): this method is used to insert a new

customer
to the
Listname,
implements
stack)
public
void data
insertNewCustomer(String
code, String
String phone)
{
customer cus = new customer(code, name, phone, null);// create new
customer
} else {//if head is not null, then assign new customer to next node
}

50

## 2.17: Method insert new customer

Method displayData (): this method is used to show all the data stored in
the data structure
@Override
public customer displayData() {
head = cus.next;//move to next node
return cus;

## 2.18: Method display data

Orderpublic
classclass
(Singly
List):
represent an order with its properties
implements
Serializable{
public String orderid;
public String ccode;
public double total;
public order next;
public order() {

## public order(String orderid, String ccode, double total) {

this.orderid = orderid;
this.ccode = ccode;
this.total = total;
}
}

51

## 2.19: Order class

Order_Controller: implements Interfaces Order and contains some
necessary methods
public class order_Controller implements IOrder {
public order head = null, tail = null;
public order first = null;
@Override

@Override
public order displayData() {}
@Override
public void saveDataToFile() {}
@Override
public void insertNewOrder(String orderid, String ccode, double total) {}
public boolean isEmpty() { }
@Override
public void sortBycusCode() {}
}
52

## 2.20: Order Controller class

Method insertNewOrder():this method is used to insert a new order to the
data structure(Singly Linked List implements queue)
@Override
public void insertNewOrder(String orderid, String ccode, double total) {
tail = new order(orderid, ccode, total); // new order will be assigned to tail
tail.next = null;//node after taill is null
if (isEmpty()) {//if data structure is null, then head , tail will be have the same
value
} else {
@Override
public order displayData() {
while (temp.next != null) {
if (isEmpty()) {// if data structure is empty, then will throw an exception
temp = temp.next;
try {
}//move to the final node of the data structure
throw new Exception();
temp.next = tail;//assgin tail to the next node
} catch (Exception ex) {
ex.printStackTrace();

}
}

## 2.21: Method insert new order

Method displayData (): this method is used to show all order in order list
return o;//return object order
}

53

## 2.22: Method display data order

OrderDetail class (Singly Linked list) represents an orderdetail with
its properties
public class orderdetail implements Serializable{
public String orderid;
public String pcode;
public String pname;
public int quantity;
public double price;
public double total;
public orderdetail next;
public orderdetail() { }
}
54

## 2.23: Order detail class

OrderDetail_Controller class: Implements Interface OrderDetail and
contains some methods
public class orderdetail_Controller implements IOrderDetail{
@Override
@Override
public orderdetail displayData() {

@Override
public void saveDataToFile() {}

@Override
public orderdetail insertNew(String orderid, String pcode,String pname, int

## value to data structure,

I catch
error
when
quantity,double
price,this
double
total)
{} insert product or customer. If null value, the

## vate void btnInsertProductActionPerformed(java.awt.event.ActionEvent evt) {

public orderdetail
insert(orderdetail
h, orderdetail order) {}
String code = pcode.getText();
String name
= pname.getText();
String txtprice= pprice.getText(); String txtquantity = pquantity.getText();
public boolean isEmpty() {}
if (!checknull(code) && !checknull(name)
&& !checknull(txtprice)
}
&& !checknull(txtquantity)) { ....................
} else {
2.24: Order Detail controller
}
2.2 implement opportunities for error handling and reporting
}
Explain about where/why/how did you apply error handling and reporting

55

If data structure is null, to prevent error there will be an inform the user click on display da

## ivate void btnDisplayProductActionPerformed(java.awt.event.ActionEvent evt) {

..
} else {
JOptionPane.showMessageDialog(rootPane, "There is nothing to show!"); } }

56

## matched, there will be an inform to the user

private void btnInsertProductActionPerformed(java.awt.event.ActionEvent
evt) {
String code = pcode.getText(); String m = "^P[0-9]{3,4}\$";
if (!checkProductCode(code)) { ...........
} else {JOptionPane.showMessageDialog(rootPane, "Code not
An inform will be displayed:
matched"); }

## which certainly existed in order list, this is an error, an inform will

be shown
private void
btnDeleteProductActionPerformed(java.awt.event.ActionEvent evt) {
String code = (String)
tableProduct.getValueAt(tblProduct.getSelectedRow(), 1);
if (!checkdeletproducteavailable(code)) {

.........

## An inform will be like

} else {JOptionPane.showMessageDialog(rootPane,
"Thisthis:
product
can not delete");}

57

## 5.When user wants to show order detail without choosing an order,

there will be a warning to make sure that user chooses an order to
view
private void
btnOrderDetailActionPerformed(java.awt.event.ActionEvent
evt) {
if (tblOrder.getSelectedRow() == -1) {
choose an order");
}

## There will be an inform:

6. When user wants to delete a product after the last one, this is an
error, an error message will be displayed to the user
private void
btnDeleteAfterCodeProductActionPerformed(java.awt.event.ActionEvent
evt) {
String code = txtDeleteAfterCode.getText();
if (pc.searchByCode(code).next != null) { .. }
else {JOptionPane.showMessageDialog(rootPane,
areinform:
at the
There will "You
be an

58

## 7.To prevent insert same product code or customer code to data

structure, I will check code before insert, if code is existed, there
will be an inform to be shown
private void
btnInsertProductActionPerformed(java.awt.event.ActionEvent evt) {
String code = pcode.getText();
if (!checkProductCode(code)) {...................
}else {JOptionPane.showMessageDialog(rootPane, "Product code
existed");}
An inform will be shown:

## 8. To prevent insert wrong type value, such as product quantity,

product price, an error warning will be displayed
private void
btnInsertProductActionPerformed(java.awt.event.ActionEvent evt) {
String txtprice= pprice.getText();
String txtquantity = pquantity.getText();
if (numberValidation(txtquantity, txtprice)) {
} else {JOptionPane.showMessageDialog(rootPane,
An inform will be shown:
}

59

Test
num
ber
1

What
is
being
tested
Product
code

Product
name

Product
quantit
y

Product
price

Custom
er code

Custom
er
name

Expected
outcome

Actual
outcome

String
Pxxx
(P002)
String
xxxx
(jeans)
Int(>=1,<
=200)
(120)

String
(P002)

Pa
Evidence
ss
or
fail
Pas Successful
s

String
(jeans)

Pas
s

Int (300)

Fail

Double(>=
1,<=3000)
(2000)
String
Cxxx
(C002)

Double
(2000)

Pas
s

String
(C00134)

Fail

String
xxxx
(Jack)

String
(Jack)

Pas
s

Successful

Successful

Successful

60

Custom
er
phone

## String (10- String

Fail
11 digits)
(09030280)
(09203021
23)

Orderid

Successful

Total
price

String
(201609090
92400)
Double
(200.0)

Pas
s

String
(20160909
092400)
Double
(200.0)

Pas
s

Successful

10

aFromFi
le()

Successful

display
Data()

file in
directory
(D:/DSA_pro
duct.txt)
Null

Pas
s

11

file in
directory
(D:/DSA_pr
oduct.txt)
Product list

12

saveDa
taToFile
()

File is
saved in
directory
(D:/DSA_pr
oduct.txt)
insertN Product
ewProd (P001,jea
uct()
ns200,200
,0)
searchB Product
yCode() (P001,jea
ns200,200
,0)

File is saved
in directory
(D:/DSA_pro
duct.txt)

Pas
s

Successful

Product
(P001,jean
s200,200,0)

Pas
s

Successful

Null

Fail

12

13

Fail

61

14

deleteB
yCode()

15

sortByC
ode()
deleteA
fterxCo
de()

16

Delete
product
(P001,jea
ns200,200
,0)
Sorted list

Delete
product
(P001,jean
s200,200,0)

Pas
s

Successful

Sorted list

Successful

Delete
product
(P001,jea
ns200,200
,0)

Null

Pas
s
Fail

17

search(
)

Product
(P001,jea
ns200,200
,0)

Null

Fail

18

aFromFi
le()

Successful

display
Data()
saveDa
taToFile
()

file in
directory
(D:/DSA_ord
er.txt)
Order list

Pas
s

19

file in
directory
(D:/DSA_or
der.txt)
Order list

successful

File is
saved in
directory
(D:/DSA_or
der.txt)
Order
(20140915
093020,C
001,2000)

File is saved
in directory
(D:/DSA_ord
er.txt)

Pas
s
Pas
s

Order
(201409150
93020,C00
1,2000)

Pas
s

Successful

Sorted

Sorted order

Pas

Successful

20

21

insertN
ewOrde
r()

22

sortByc

Successful

62

order list

list

file in
directory
(D:/DSA_cu
stomer.txt)
Customer
list

Pas
file in
s
directory
(D:/DSA_cust
omer.txt)
Null
Fail

Successful

File is
saved in
directory
(D:/DSA_cu
stomer.txt)
insertN Customer
ewCust (C001,Ng
omer()
uyen,0903
020293)
searchB Customer
yCode() (C001,Ng
uyen,0903
020293)

## File is saved Pas

in directory
s
(D:/DSA_cust
omer.txt)

Successful

Customer
(C001,Ngu
yen,090302
0293)
Null

Pas
s

Successful

28

deleteB
yCode()

Pas
s

Successful

29

aFromFi
le()

Delete
customer
(C001,Ngu
yen,090302
0293)
file in
directory
(D:/DSA_ord

Pas
s

Successful

23

usCode
()
aFromFi
le()

24

display
Data()

25

saveDa
taToFile
()

26

27

Delete
customer
(C001,Ng
uyen,0903
020293)
file in
directory
(D:/DSA_or

Fail

63

30

display
Data()
saveDa
taToFile
()

31

32

insertN
ew()

de4rdetail.t
xt)
Orderdetail
list
File is
saved in
directory
(D:/DSA_or
derdetail.tx
t)
Orderdetail
(20140915
093020,P
001,
Jeans,100
,2,200)

erdetail.txt)
Orderdetail
list
File is saved
in directory
(D:/DSA_ord
erdetail.txt)

Pas
s
Pas
s

Successful

Orderdetail
(201409150
93020,P00
1,
Jeans,100,2
,200)

Pas
s

Successful

Successful

System Requirements
Windows XP or later,Linux, MacOS
RAM: 128 MB; 64 MB for Windows XP (32-bit)
Disk space: 124 MB
JDK 6 or later
Compiling and running program
Compile the program from within the directory:
javac DSA_A1.java

After compiling the program successfully, run it from the directory above:
java DSA_A1

64

## Here is a user interface when programme is loaded. Tab product

will be shown first

7
5
8

2
4
6

12

1
3

9
1
0

14
1
1

65

## 1: This button is used to load data from file

2: This button is used to save data to file and exit
3: This button is used to search product code in the data structure and
return found value to the table
4: Move to tab Order
5: Move to tab Customer
6: This button is used to delete product after code
7: Move to tab Product
8: Click on this button will open an insert product window
9: This will delete product which is selected in the product table
10: Click on this button will sort the data structure by product code
11: Click on this button will show all the value in the data structure
12: A textfield accept product code to be deleted after that
13: A textfield accept product code to be searched
14: This table is used to display products in the data structure

66

1
2

code

name

quantity

## 4: Text field accept product

price
5: Click this button will

67

5
6

8
9
1
0

1
1

## 1: This button is used to load data from file

2: This button is used to save data to file and exit programme
3: Click on this button will search customer in data structure by customer
code
4: Textfield accept customer code to be searched
5: Move to tab product
6: Move to tab customer

68

## 7: Move to tab order

8: Click on this button will open an insert customer window
9: Click on this button will delete customer which is selected in the
customer table
10: Click on this button will display all data on the table
11: Table will be used to display data

## Insert new customer

1: Text field accept
customer code

1
2
3
4

## 2: Text field accept

customer name
3: Text field accept
customer phone number
4: Click on this button will
close this window
5: Click on this window will
insert new customer to the
data structure

69

3
7

1
4

2
6

8
9

1
0

## 1: This button is used to load data from file

2: This button is used to save data to file and exit programme
3: Move to tab Product
4: Move to tab Customer
5: Move to tab Order

70

6: Click on this button will sort customers in the data structure and will
show in the table
7: Click on this button will open an insert order window
8: Click on this button will display all data in the table
9: Click on this button will show order detail which is selected in the table
10: Table is used to display all orders in the data structure
Input new order

71

8
1
0

## 1: Select customer code who is ordering

2: Select product code which is ordered
3: Input product quantity
4: This will show product price
5: This will show total price

72

6: Click on this button will add product to order list and will show in the
table
7: This table is used to show products in order list
8: This will show total price of the order
9: Click on this button will make ordering
10: Click on this button will close this window
Order detail
1: This will show orderid

total

## 3: This will show customer

code
4: This will show customer
name

5
6

## 5: This table is used to

show list product in an
order
6: Click on this button will
close this window

START

FILE

73

PRODUCT

INSERT

CUSTOMER

DELETE

SORT

ORDER

SEARCH

DISPLAY

SAVE DATA TO
FILE

END

## SMS FLOW CHART

Positive: This programme is very simple, easy to handle, admin can fix any
error anytime
Negative:
Dont handle the amount of products saled per day and also the amount of
customers
74

## Manage customers but dont do anything with them, customers

information is not clear, lacking of address, email or something else like
that
There should be an order status so that the manager could manage orders
easily
Beside that, the order can be canceled also

75