This commit is contained in:
louiscklaw
2025-02-01 01:58:47 +08:00
parent b3da7aaef5
commit 04dbefcbaf
1259 changed files with 280657 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
public class DuplicateValException extends RuntimeException{
public DuplicateValException(){
super("Duplicate value");
}
}

View File

@@ -0,0 +1,5 @@
class EmptyListException extends Exception {
public EmptyListException(){
super("Empty List");
}
}

View File

@@ -0,0 +1,253 @@
public class LinkedList {
private ListNode head;
private ListNode tail;
public LinkedList() {
head = null;
tail = null;
}
public boolean isEmpty() {
return (head == null);
}
public void addToHead(Object item) {
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
head = new ListNode(item, head);
}
}
public void addToTail(Object item) {
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
tail.next = new ListNode(item);
tail = tail.next;
}
}
public Object removeFromHead() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
Object item = head.data;
if (head == tail) {
head = tail = null;
} else {
head = head.next;
}
return item;
}
public String toString() {
String s = "[ ";
ListNode current = head;
while (current != null) {
s += current.data + " ";
current = current.next;
}
return s + "]";
}
public Object removeFromTail() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
Object item = tail.data;
if (head == tail) {
head = tail = null;
return item;
}
ListNode current = head;
while (current.next != tail) {
current = current.next;
}
tail = current;
tail.next = null;
return item;
}
public int getCount() {
int count = 0;
ListNode current = head;
while (current != null) {
count++;
current = current.next;
}
return count;
}
public void addItemAt(Object item, int n) {
if (isEmpty() || n == 0) {
head = new ListNode(item, head);
return;
}
if (n >= getCount()) {
tail.next = new ListNode(item);
} else {
int currentPos = 0;
ListNode current = head;
while (currentPos != (n - 1)) {
current = current.next;
currentPos++;
}
ListNode newNode = new ListNode(item);
newNode.next = current.next;
current.next = newNode;
}
}
public Object removeItemAt(int n) throws EmptyListException {
if (n < 0 || n > getCount()) {
throw new IndexOutOfBoundsException();
}
if (n == 0) {
return (removeFromHead());
}
int currentPos = 0;
ListNode current = head;
while (currentPos < (n - 1)) {
current = current.next;
currentPos++;
}
Object item = current.next.data;
current.next = current.next.next;
return item;
}
public Object getItemAt(int n) {
if (n < 0 || n > getCount()) {
throw new IndexOutOfBoundsException();
}
int currentPos = 0;
ListNode current = head;
while (currentPos < n) {
current = current.next;
currentPos++;
}
return current.data;
}
public int searchItemAt(Object item) { // search the item position
ListNode current = head; // create the pointer to head
int currentPos = 0; // let the position as 0, the linkedlist with start at 0
while (current != null) { // search the item until the linkedlist tail -> null
if (current.data == item) { // if found the same data in the linkedlist will break
break;
}
current = current.next;
currentPos++; // if current data is not equal to we may found data so the position will add 1 to calculate current Node position.
}
return currentPos; // return the search item position
}
public boolean checkDup(){
ListNode current=head;
boolean checkDup = false;
while (current!=null){
ListNode currentSec = current.next;
while(currentSec !=null){
if(current.data.equals(currentSec.data)){
checkDup = true;
break;
}
currentSec= currentSec.next;
}
if(checkDup)
break;
current=current.next;
}
return checkDup;
}
public void findJokerA() throws EmptyListException { // switch the card 27 and 27 next card
if (tail.data.equals(27)) { // In special case, if the tail data is 27
Object cache = head.data; // cache the data of head data, because the tail data will replcae the head data when the card switch
tail.data = cache; // tail data will equal to head data when the card switch
head.data = 27; // head data equal the 27 when the case of 27 is tail data
} else {
ListNode current = head; // create the pointer to head of ListNode
while (!current.data.equals(27)) { // find the ListNode position and the ListNode data is 27
current = current.next; // if ListNode data is not 27 will point to next Node
}
Object cache = current.next.data; // set the cache data of next current position
current.data = cache; // current position set to data of next current position
current.next.data = 27; // the next current position set to 27
}
}
public void findJokerB() throws EmptyListException {// switch the card 28, 28 next card and 28 next next card
if (tail.data.equals(28)) { // In special case, if the tail data is 28
Object cache = head.data; // set cache data of head data, because the tail data will replcae the head data when the card switch
tail.data = cache; // tail data will set to head data
head.data = head.next.data; // The head data will set to head next data
head.next.data = 28; // The head next data will set to 28
} else if (searchItemAt(28) == 26) { // In special case, if the tail before data is 28
Object cachetail = removeFromTail(); // set the cache data of Tail data and remove tail data
tail.data = cachetail; // In currenly, the total count card is 27. The tail data set to cache data (remove tail data in line 171)
addToTail(head.data); // Add to tail of head data in the LinkedList and the total count card is 28
head.data = 28; // set the 28 is head data.
} else {
ListNode current = head; // create the pointer to head of ListNode
while (!current.data.equals(28)) { // find the ListNode position and the ListNode data is 28
current = current.next; // if ListNode data is not 28 will point to next Node
}
Object cache = current.next.data; // set cache data is current next data and current next next data
Object cacheTwo = current.next.next.data;
current.data = cache; // current data position is 28 so set the data to current next data
current.next.data = cacheTwo; // 28 after data set to current next next data
current.next.next.data = 28; // the current next next data set to 28
}
}
public void tripleCut() throws EmptyListException {
LinkedList cacheLeft = new LinkedList(); //Create the LinkedList to store cut data in Left and Right
LinkedList cacheRight = new LinkedList();
int listRightSize, listLeftSize;
if (searchItemAt(27) > searchItemAt(28)) { // search the data is 27 and 28, if the 27 position larger that of 28 position will cut right hand site(Tail), and the 28 will left hand site(Head)
listRightSize = getCount() - searchItemAt(27) - 1; // calcuate the 27 how many value should cut
listLeftSize = searchItemAt(28); // the 28 should cut the current position value
} else { // otherwise the 28 position larger that of 27 position will cut right hand site(Tail) and the 27 will cut left hand site(Head)
listRightSize = getCount() - searchItemAt(28) - 1; // calcuate the 28 how many value should cut
listLeftSize = searchItemAt(27); // the 27 should cut the current position value
}
for (int i = 0; i < listRightSize; i++) {
cacheRight.addToTail(removeFromTail()); //cut right hand sit and put the value to cacheRight LinkedList
}
for (int i = 0; i < listLeftSize; i++) {
cacheLeft.addToTail(removeFromHead()); // cut left hand sit and put the value to cacheLeft LinkedList
}
for (int i = 0; i < listRightSize; i++) {
addToHead(cacheRight.removeFromHead()); // store all value of cacheRight LinkedList to Left Hand site (Head)
}
for (int i = 0; i < listLeftSize; i++) {
addToTail(cacheLeft.removeFromHead()); // store all vale of cacheLeft LinkedList to Right Hand site (Tail)
}
}
public void countCut() throws EmptyListException {
if (tail.data.equals(28)) { // if tail data is 28
return; // Not to do
} else {
Object item = removeFromTail(); // remove the tail data and store the value to item
for (int i = 0; i < (int) item; i++) { // According the item value to put the head Node to Tail Node of number
addToTail(removeFromHead());
}
addToTail(item); // put the item value(in line 219) to Tail.
}
}
public Object topCard() throws EmptyListException {
if (head.data.equals(28)|| head.data.equals(27)) { //when the head data is 28 or 27 will return the tail data
return tail.data;
} else { // the head data is not 28 or 28 will return the search of head data position
return getItemAt((int) head.data);
}
}
}

View File

@@ -0,0 +1,16 @@
public class ListNode {
Object data;
ListNode next;
public ListNode(){
data=null;
next=null;
}
public ListNode(Object data){
this.data = data;
this.next = null;
}
public ListNode(Object data, ListNode next){
this.data = data;
this.next = next;
}
}

View File

@@ -0,0 +1,5 @@
public class NotJokerException extends RuntimeException{
public NotJokerException(){
super("Not Joker");
}
}

View File

@@ -0,0 +1,5 @@
public class NotMatchTypeException extends RuntimeException {
public NotMatchTypeException(){
super("Total card should be 28 and Integer number");
}
}

View File

@@ -0,0 +1,11 @@
# ITP4510-Assignment
ITP4510 Data Structures &amp; Algorithms: Concepts &amp; Implementation
### Setup
```
$ javac SolitaireEncryption.java
```
### Usage
```
$ java SolitaireEncryption <option(en|de|keygen)> <deck_File_Path> <message_string>
```

View File

@@ -0,0 +1,122 @@
// Name: Kwok Ho Hin
// Student ID: 180160427
// Program code-Class: IT114105-1B
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SolitaireEncryption {
public static void main(String[] args) {
try {
LinkedList qll = new LinkedList(); //Object of LinkedList
Scanner input = new Scanner(new File(args[1]));
while (input.hasNextInt()) { //if the text file has Integer will put to qll LinkedList, when the text file contain other data type will stop input
qll.addToTail(input.nextInt());
}
input.close();
if (qll.getCount() != 28) { //check the qll whether 28 card, if not 28 card will Stop the program
throw new NotMatchTypeException();
}
if (qll.searchItemAt(27) == 28 || qll.searchItemAt(28) == 28) {
throw new NotJokerException(); // check the qll whether contain Joker
}
if (qll.checkDup()) {
throw new DuplicateValException(); // check the qll whether contain Duplicate Value
}
if (args[0].equals("keygen") || args[0].equals("en") || args[0].equals("de")) { //args[0] should be 3 type: keygen, en or de
keygen(args[2], qll, args[0]);
} else {
System.out.println("Sorry: keygen||en||de FileLocation Word"); //not keygen, en or de
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found in " + args[1]); //Can not found the File so throw FileNotFoundException
} catch (IndexOutOfBoundsException e) {
System.out.println("Can not Encryption or Decryption the message"); //Encryption and Decryption use the array to store the message so it may throw IndexOutOfBoundsException
} catch (DuplicateValException e) {
System.out.println("Text file contain Duplicate value"); //Duplicate value
} catch (NotMatchTypeException e) {
System.out.println("Total card should be 28 and Integer number"); //Number of card is not 28 so throw NotMatchTypeException
} catch (NotJokerException e) {
System.out.println("Not contain all Joker (27, 28)");
} catch (EmptyListException e) {
System.out.println("Empty List"); //when the LinkedList remove the node so it may EmptyListException occure
} catch (Exception e) {
System.out.println("Unknow Error");
}
}
public static void keygen(String args, LinkedList qll, String type) throws EmptyListException {
LinkedList keystreamVal = new LinkedList(); //Create the LinkedList to store the keystream Value
args = args.replaceAll("\\s", "").toUpperCase(); //Trim the String of the args[2] and change to Upper Case.
for (int i = 0; i < args.length(); i++) { //each args[2] Sting will generate the keystream Value
qll.findJokerA(); //call the LinkedList method to findJokerA
keygenPrint("S1: ", type, qll); //check the args[0] wether "keygen"
qll.findJokerB(); //call the LinkedList method to findJokerB
keygenPrint("S2: ", type, qll); //check the args[0] wether "keygen"
qll.tripleCut(); //call the LinkedList method to cut the card
keygenPrint("S3: ", type, qll); //check the args[0] wether "keygen"
qll.countCut(); //call the LinkedList method to count cut
keygenPrint("S4: ", type, qll); //check the args[0] wether "keygen"
if (!qll.topCard().equals(28) && !qll.topCard().equals(27)) { //call the LinkedList method and return the keystream value, if keystream value not 27 or 28
keygenPrint("Key " + (i + 1) + ": ", type, qll.topCard()); //check the args[0] wether "keygen"
keystreamVal.addToTail(qll.topCard()); //add the keystreamVal to keystreamVal LinkedList
} else {
keygenPrint("Joker", type, qll); //check the args[0] wether "keygen"
i--; //if Is Joker will skip this position so i--
}
}
if (type.equals("en") || type.equals("de")) { //check wether "en" or "de" and wether keep running
message(args, keystreamVal, type);
} else {
System.out.println("Keystream values:" + keystreamVal); //Keystream values
}
}
public static void message(String args, LinkedList keystreamVal, String type) throws EmptyListException {
Object[] message = new Object[args.length()]; // set the message array to store encryption or decryption message
int sum = 0; // set each encryption or decrpytion message vale of 0
for (int i = 0; i < args.length(); i++) { // each char will encryption or decrpytion
System.out.print(args.charAt(i) + "\t" + (letter().searchItemAt(args.charAt(i)) + 1) + "\t" + keystreamVal.getItemAt(i)); // print the current char, and char number and keystream Value
if (type.equals("en")) { // Encrpytion Procedure
sum = (int) keystreamVal.getItemAt(i) + (int) (letter().searchItemAt(args.charAt(i)) + 1); // keystream + char number and store in sum Varible
if (sum > 26) { // if the sum is > 26 should be -26
sum -= 26;
}
} else if (type.equals("de")) { // Decrpytion Procedure
sum = (int) (letter().searchItemAt(args.charAt(i)) + 1) - (int) keystreamVal.getItemAt(i); // Char number - keystream Value and store in sum Varible
if (sum < 1) { // if the sum is < 0 should be +26
sum += 26;
}
}
message[i] = (letter().getItemAt((sum - 1))); // store the all encrypted or decrypted message in message array
System.out.print("\t" + sum + "\t" + (letter().getItemAt(sum - 1)) + "\n"); // print the encrypted or decrypted message and char
if (i == args.length() - 1 && type.equals("en")) { // print the encrypted or decrypted message in message array
System.out.print("Encrypted message: ");
} else if (i == args.length() - 1 && type.equals("de")) {
System.out.print("Decrypted message: ");
}
}
for (int i = 0; i < message.length; i++) {
System.out.print(message[i]);
}
}
public static void keygenPrint(String number, String type, Object qll) {
if (type.equals("keygen") && !number.equals("Joker")) { //check wether keygen and print the linkedList
System.out.println(number + ":" + qll);
} else if (type.equals("keygen") &&number.equals("Joker")) {
System.out.println(number + ": Key skipped");
}
}
public static LinkedList letter() {
LinkedList letter = new LinkedList(); //set the LinkedList to store the A-Z char
for (char alph = 'A'; alph <= 'Z'; alph++) {
letter.addToTail(alph);
}
return letter;
}
}

View File

@@ -0,0 +1 @@
1 4 7 10 13 16 19 22 25 28 3 6 9 12 15 18 21 24 27 2 5 8 11 14 17 20 23 26

View File

@@ -0,0 +1 @@
21 16 10 9 5 1 13 14 17 22 23 4 20 28 6 2 24 19 15 27 18 26 25 11 12 7 8 3

View File

@@ -0,0 +1 @@
13 10 19 25 8 12 20 18 26 1 9 22 15 3 17 24 2 21 23 27 7 14 5 4 28 11 16 6

View File

@@ -0,0 +1,2 @@
28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

View File

@@ -0,0 +1 @@
18 27 2 8 26 23 24 17 22 21 4 25 9 15 3 19 14 12 5 13 1 7 10 16 6 1 20 28

View File

@@ -0,0 +1 @@
27 4 22 10 15 9 7 13 12 19 26 25 20 6 18 8 2 17 21 3 23 11 14 24 1 16 28 5

View File

@@ -0,0 +1,2 @@
5 4 22 10 15 9 7 13 12 19 26 25 20 6 18 8 2 17 21 3 23 11 14 24 1 28 16 27

View File

@@ -0,0 +1 @@
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

View File

@@ -0,0 +1,3 @@
public interface AdminFunction {
public void execute();
}

View File

@@ -0,0 +1,18 @@
public class AdminPrintOrderList implements AdminFunction{
private LinkedList orders;
public AdminPrintOrderList(LinkedList orders){
this.orders = orders;
}
@Override
public void execute() {
// TODO Auto-generated method stub
System.out.println("--------------------------------------");
System.out.println(orders);
System.out.println("--------------------------------------");
System.out.println("Total outstanding order:" + orders.count());
}
}

View File

@@ -0,0 +1,17 @@
public class AdminRemoveOrder implements AdminFunction{
private int memberId;
private LinkedList orders;
public AdminRemoveOrder(int memberId, LinkedList orders) {
this.memberId = memberId;
this.orders = orders;
}
@Override
public void execute() {
// TODO Auto-generated method stub
orders.remove(memberId);
}
}

View File

@@ -0,0 +1,48 @@
public class FoodOrder {
private int memberID;
private String foodOrder; // A, B, C, or D
private int priority;
//constructor
public FoodOrder(int memberID){
this.memberID = memberID;
}
public FoodOrder(int memberID, String foodOrder) {
this.memberID = memberID;
this.foodOrder = foodOrder;
priority = 2;
}
//provide methods getter, setter, toString ....
public int getMemberID() {
return this.memberID;
}
public void setMemberID(int memberID) {
this.memberID = memberID;
}
public String getFoodOrder() {
return this.foodOrder;
}
public void setFoodOrder(String foodOrder) {
this.foodOrder = foodOrder;
}
public int getPriority() {
return this.priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public String toString(){
return "[ MemberID: " + memberID + " ordered Set " + foodOrder + " with priority " + priority + " ]";
}
}

View File

@@ -0,0 +1,10 @@
public class InvalidInputException extends Exception{
public InvalidInputException(String mes){
super(mes);
}
public InvalidInputException(){
super("Invalid input! Please input again.");
}
}

View File

@@ -0,0 +1,193 @@
class ListNode {
private Object data;
private ListNode next;
public ListNode(Object o) { data = o; next = null; }
public ListNode(Object o, ListNode nextNode)
{ data = o; next = nextNode; }
public Object getData() { return data; }
public void setData(Object o) { data = o; }
public ListNode getNext() { return next; }
public void setNext(ListNode next) { this.next = next; }
} // class ListNode
class EmptyListException extends RuntimeException {
public EmptyListException ()
{ super("List is empty"); }
} // class EmptyListException
public class LinkedList {
private ListNode head;
private ListNode tail;
private int length; // the length of the list
public LinkedList() {
head = tail = null;
length = 0;
}
public boolean isEmpty() { return head == null; }
public void addToHead(Object item) {
if (isEmpty())
head = tail = new ListNode(item);
else
head = new ListNode(item, head);
length++;
}
public void addToTail(Object item) {
if (isEmpty())
head = tail = new ListNode(item);
else {
tail.setNext(new ListNode(item));
tail = tail.getNext();
}
length++;
}
public Object removeFromHead() throws EmptyListException {
Object item = null;
if (isEmpty())
throw new EmptyListException();
item = head.getData();
if (head == tail)
head = tail = null;
else
head = head.getNext();
length--;
return item;
}
public Object removeFromTail() throws EmptyListException {
Object item = null;
if (isEmpty())
throw new EmptyListException();
item = tail.getData();
if (head == tail)
head = tail = null;
else {
ListNode current = head;
while (current.getNext() != tail)
current = current.getNext();
tail = current;
current.setNext(null);
}
length--;
return item;
}
public int count() {
return length;
}
// students need to revise toString method
public String toString() {
String str = "";
ListNode current = head;
while (current != null) {
FoodOrder foodOrder = (FoodOrder) current.getData();
str += foodOrder + "\n";
current = current.getNext();
}
return str;
}
/**
Removes a ListNode from the LinkedList with a specific Member ID.
@param targetID the Member ID of the ListNode to be removed
@throws EmptyListException if the list is empty
*/
public void remove(int targetID) throws EmptyListException {
// Throw an exception if the list is empty
if (isEmpty()) {
throw new EmptyListException();
}
// If the target node is the head node, remove it from the head
if (((FoodOrder) head.getData()).getMemberID() == targetID) {
removeFromHead();
return;
}
// Traverse the linked list to find the target node
ListNode current = head.getNext();
ListNode prev = head;
while (current != null && ((FoodOrder) current.getData()).getMemberID() != targetID) {
prev = current;
current = current.getNext();
}
// If the target node is found, remove it
if (current != null) {
prev.setNext(current.getNext());
length--;
}
}
/**
Checks if the linked list contains a FoodOrder object with the given targetID as its member ID.
@param targetID the member ID to search for in the linked list
@return true if the linked list contains a FoodOrder object with the given targetID as its member ID, false otherwise
*/
public boolean contain(int targetID) {
ListNode current = head;
while (current != null) {
if (((FoodOrder) current.getData()).getMemberID() == targetID) {
return true;
}
current = current.getNext();
}
return false;
}
/**
Adds a new FoodOrder to the LinkedList in the correct position based on its priority.
@param item the FoodOrder to add to the LinkedList
*/
public void add(Object item) {
FoodOrder foodOrderItem = (FoodOrder) item;
// if the list is empty, add the new node as the head
if (isEmpty())
addToHead(item);
// if the new node has higher priority than the head, add it as the new head
else if (foodOrderItem.getPriority() < ((FoodOrder) head.getData()).getPriority())
addToHead(item);
// if the new node has lower priority than the tail, add it as the new tail
else if (foodOrderItem.getPriority() >= ((FoodOrder) tail.getData()).getPriority())
addToTail(item);
// otherwise, find the correct position for the new node and insert it
else {
ListNode current = head.getNext();
ListNode prev = head;
while (current != null && foodOrderItem.getPriority() >= ((FoodOrder) current.getData()).getPriority()) {
prev = current;
current = current.getNext();
}
prev.setNext(new ListNode(item, current));
length++;
}
}
}

View File

@@ -0,0 +1,16 @@
public class MenuItem {
private String food;
public MenuItem(String food){
this.food = food;
}
public String getMenuItemFood(){
return this.food;
}
public String toString(){
return food;
}
}

View File

@@ -0,0 +1,5 @@
public class NoneOfOrderException extends InvalidInputException {
public NoneOfOrderException(){
super("None of order");
}
}

View File

@@ -0,0 +1,153 @@
import java.util.Scanner;
public class OrderSystem {
private static Scanner sc;
private static LinkedList orders;
private static int nextGuestID = 9000;
private static MenuItem[] menus;
private static FoodOrder currentFoodOrder;
public static void main(String[] args) {
sc = new Scanner(System.in);
orders = new LinkedList();
regFoodMenu();
while (true) {
start();
}
}
private static void regFoodMenu() {
menus = new MenuItem[4];
menus[0] = new MenuItem("Chicken Salad");
menus[1] = new MenuItem("Grilled Ribeye Steak");
menus[2] = new MenuItem("Angel Hair Pasta with Shrimp");
menus[3] = new MenuItem("Grilled Fish and Potatoes");
}
public static void start() {
try {
int memberId = inputMemberId(false);
if (memberId <= -1) {
System.err.println("Have a nice day!!!");
System.exit(1);
}
if (memberId == 9999) {
adminFunc();
} else {
currentFoodOrder = new FoodOrder(memberId);
if (memberId == 0) {
memberId = nextGuestID++;
currentFoodOrder.setMemberID(memberId);
currentFoodOrder.setPriority(3);
} else if (memberId > 8000 && memberId < 8200)
currentFoodOrder.setPriority(1);
else if (memberId > 8199 && memberId < 9000)
currentFoodOrder.setPriority(2);
inputOrder();
}
} catch (InvalidInputException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void printMenu() {
System.out.println("----------------- Food Menu ----------------");
for (int dec = 65, i = 0; i < menus.length; dec++)
System.out.println("Set " + (char) dec + " : " + menus[i++]);
System.out.println("--------------------------------------------");
}
public static void printAdminMenu() {
System.out.println("----------------- Admin Function ----------------");
System.out.println("1 : Print order list");
System.out.println("2 : Remove order");
}
public static int inputMemberId(boolean isAdmin) throws InvalidInputException {
try {
if(isAdmin){
System.out.print("Enter Member ID:");
int memberId = Integer.parseInt(sc.nextLine());
if ( memberId > 8000 && memberId < 9999)
return memberId;
}else{
System.out.print("Please input your member ID [input 0 for guest]:");
int memberId = Integer.parseInt(sc.nextLine());
if (memberId <= 0 || memberId == 9999 || memberId > 8000 && memberId < 8999)
return memberId;
}
} catch (NumberFormatException e) {
System.out.println("Input Error");
System.exit(1);
}
throw new InvalidInputException();
}
public static void inputOrder() throws InvalidInputException {
printMenu();
System.out.print("Select food:");
String foodOrder = sc.nextLine().toUpperCase();
if (!isValidFoodOrderChar(foodOrder))
throw new InvalidInputException();
currentFoodOrder.setFoodOrder(foodOrder);
orders.add(currentFoodOrder);
}
private static boolean isValidFoodOrderChar(String foodOrder) {
if (foodOrder.length() > 2 || foodOrder.length() == 0)
return false;
char value = foodOrder.charAt(0);
return (value >= 65 && value <= 65 + menus.length)? true: false;
}
public static void adminFunc() throws InvalidInputException {
try {
printAdminMenu();
System.out.print(">");
int adminFuncInput = Integer.parseInt(sc.nextLine());
if (!isValidAdminFunction(adminFuncInput))
throw new InvalidInputException();
if (adminFuncInput == 1)
new AdminPrintOrderList(orders).execute();
else if (adminFuncInput == 2) {
int memberId = inputMemberId(true);
if (!orders.contain(memberId))
throw new NoneOfOrderException();
new AdminRemoveOrder(memberId, orders).execute();
} else
throw new InvalidInputException();
} catch (NumberFormatException e) {
throw new InvalidInputException();
}
}
private static boolean isValidAdminFunction(int input) {
return (input == 1 || input == 2)? true: false;
}
}

View File

@@ -0,0 +1,278 @@
# ITP4510-Assignment
ITP4510 Data Structures &amp; Algorithms: Concepts &amp; Implementation
## Scenarios
The Yummy Restaurant Group Limited is a catering company. It has grown into one of the largest catering company in Hong Kong. The Group is operating diversified services including Chinese Restaurants, Western Restaurants, Japanese Restaurants, Conveyor-belt Sushi Restaurants, Fast Food Restaurants and etc. It has over 10 brands and around 100 restaurants in 2021.
The Novel House, which located in the Clover Hotel, is belonged to Yummy Restaurant Group Limited. For the Novel House, customer can place food order by phone. The operator will enter the order information in the system. For each of the food order, a priority indicator will be assigned to it. The least priority indicator of the food order will be first delivered, however, if the food orders with the same priority occurred, the food will be delivered according to their ordering in the queue.
Now, one IT staff is assigned to develop a prototype program to simulate the ordering of the food.
## Membership
List of Priority Indicator
| Membership | Priority Indicator |
| -- | -- |
| VIP Member | 1 |
| Registered Member | 2 |
| Guest | 3 |
Member ID is a four digit number starting with “8”. Member ID of VIP members should be started from 8001 to 8199. The Member ID of registered members should be in the range of 8200 to 8999. The Member ID for a guest would be an increment number started from 9000.
## Food Menu
| Set | Food |
| -- | -- |
| A | Chicken Salad |
| B | Grilled Ribeye Steak |
| C | Angel Hair Pasta with Shrimp |
| D | Grilled Fish and Potatoes |
## Execution Sample
```
_Number_ <- present the user input
```
### 1. Process Ordering
```
Please input your member ID [input 0 for guest]:_0_ ← Order by guest
----------------- Food Menu ----------------
Set A : Chicken Salad
Set B : Grilled Ribeye Steak
Set C : Angel Hair Pasta with Shrimp
Set D : Grilled Fish and Potatoes
--------------------------------------------
Select food:_a_
Please input your member ID [input 0 for guest]:_8101_ ← Order by VIP
----------------- Food Menu ----------------
Set A : Chicken Salad
Set B : Grilled Ribeye Steak
Set C : Angel Hair Pasta with Shrimp
Set D : Grilled Fish and Potatoes
--------------------------------------------
Select food:_b_
Please input your member ID [input 0 for guest]:_8103_ ← Order by VIP
----------------- Food Menu ----------------
Set A : Chicken Salad
Set B : Grilled Ribeye Steak
Set C : Angel Hair Pasta with Shrimp
Set D : Grilled Fish and Potatoes
--------------------------------------------
Select food:A
Please input your member ID [input 0 for guest]:_8299_ ← Order by registered member
----------------- Food Menu ----------------
Set A : Chicken Salad
Set B : Grilled Ribeye Steak
Set C : Angel Hair Pasta with Shrimp
Set D : Grilled Fish and Potatoes
--------------------------------------------
Select food:_d_
Please input your member ID [input 0 for guest]:_0_ ← Order by guest
----------------- Food Menu ----------------
Set A : Chicken Salad
Set B : Grilled Ribeye Steak
Set C : Angel Hair Pasta with Shrimp
Set D : Grilled Fish and Potatoes
--------------------------------------------
Select food:_a_
Please input your member ID [input 0 for guest]:_8233_ ← Order by registered member
----------------- Food Menu ----------------
Set A : Chicken Salad
Set B : Grilled Ribeye Steak
Set C : Angel Hair Pasta with Shrimp
Set D : Grilled Fish and Potatoes
--------------------------------------------
Select food:_B_
```
### 2. Print out Order List
```
Please input your member ID [input 0 for guest]: _9999_
----------------- Admin Function ----------------
1 : Print order list
2 : Remove order
>_1_
--------------------------------------
[ MemberID: 8101 ordered Set B with priority 1 ]
[ MemberID: 8103 ordered Set A with priority 1 ]
[ MemberID: 8299 ordered Set D with priority 2 ]
[ MemberID: 8233 ordered Set B with priority 2 ]
[ MemberID: 9000 ordered Set A with priority 3 ]
[ MemberID: 9001 ordered Set A with priority 3 ]
--------------------------------------
Total outstanding order:6
```
### 3. Delete Order
```
Please input your member ID [input 0 for guest]:_9999_
----------------- Admin Function ----------------
1 : Print order list
2 : Remove order
>_2_
Enter Member ID:8299
Please input your member ID [input 0 for guest]:_9999_
----------------- Admin Function ----------------
1 : Print order list
2 : Remove order
>_1_
--------------------------------------
[ MemberID: 8101 ordered Set B with priority 1 ]
[ MemberID: 8103 ordered Set A with priority 1 ]
[ MemberID: 8233 ordered Set B with priority 2 ]
[ MemberID: 9000 ordered Set A with priority 3 ]
[ MemberID: 9001 ordered Set A with priority 3 ]
--------------------------------------
Total outstanding order:5
```
### 4. Quit Program
```
Please input your member ID [input 0 for guest]:_-1_
Have a nice day!!!
```
Type any negative number in the main menu to quit the program.
## Validation for Input
You should create an exceptional class `InvalidInputException` for the program. During the ordering stage, the program should do the validation for the following cases:
1. Checking valid range of Member ID
2. Checking selection of food
3. Deleting of order
```
Please input your member ID [input 0 for guest]:_523_
Invalid input! Please input again.
Please input your member ID [input 0 for guest]:_7569_
Invalid input! Please input again.
Please input your member ID [input 0 for guest]:_9856_
Invalid input! Please input again.
Please input your member ID [input 0 for guest]:_0_
----------------- Food Menu ----------------
Set A : Chicken Salad
Set B : Grilled Ribeye Steak
Set C : Angel Hair Pasta with Shrimp
Set D : Grilled Fish and Potatoes
--------------------------------------------
Select food:_f_
Invalid input! Please input again.
Please input your member ID [input 0 for guest]:_9999_
----------------- Admin Function ----------------
1 : Print order list
2 : Remove order
>_2_
Enter Member ID:_8231_ ← This order is not exist in the LinkedList
None of order
```
Program would be stopped when entered non-number in the main menu.
```
Please input your member ID [input 0 for guest]:_Abcd_
Input Error
```
## Given Files
1. `OrderSystem.java` *main program which should be completed*
2. `LinkedList.java` *data structure which should be amended*
3. `FoodOrder.java` *data type for the data object stored in ListNode*
## Task Specification
1. You should use the classes provided in the given files.
2. Implement the program using Java. Submit listings of all programs.
3. Handle exceptional/abnormal cases. You should create your own Exception class. Submit a brief description of all such cases (e.g. invalid input ) handled by the program. A class InvalidInputException should be implemented.
4. Program structure and in-program comments.
5. Evidence of testing. Test the program and submit the logged listing of run samples.
## Mark Allocation
<table>
<tbody><tr>
<td>
<p>0. Compilation</p>
<p>-- success compilation and execute the program</p>
</td>
<td>
<p>10%</p>
</td>
</tr>
<tr>
<td>
<p>1. Design</p>
<p>-- correct using class <span >FoodOrder</span>, LinkedList,
<span >ListNode</span></p>
<p>-- suitable data
structure</p>
</td>
<td >
<p>10%</p>
</td>
</tr>
<tr style="mso-yfti-irow:2">
<td>
<p>2. Implementation</p>
<p>-- input parameter</p>
<p>-- program simulation</p>
<p>-- result print out</p>
</td>
<td >
<p>45%</p>
</td>
</tr>
<tr>
<td>
<p>3. Selection of menu</p>
<p>-- Correct menu design</p>
</td>
<td>
<p>10%</p>
</td>
</tr>
<tr>
<td>
<p>4. Error handling</p>
<p>-- create exception class InvalidRangeInputException</p>
<p>-- handle exception (e.g.InputMismatchException>)</p>
</td>
<td>
<p>10%</p>
</td>
</tr>
<tr>
<td>
<p>5. Report</p>
<p>-- executable results (screen dumps)</p>
</td>
<td>
<p>5%</p>
</td>
</tr>
<tr>
<td>
<p>6. Coding standard</p>
<p>-- proper indentation</p>
<p>-- proper naming</p>
<p>-- consistency coding style</p>
<p>-- appropriate comments</p>
</td>
<td>
<p>10%</p>
</td>
</tr>
<tr>
<td>
<p><b>Total</b></p>
</td>
<td>
<p>100%<o:p></b></p>
</td>
</tr>
</tbody></table>
## Instructions to Students
This assignment is an individual assignment. Each student has to submit his/her own work. Plagiarism will be treated seriously. All assignments that have been found involved wholly or partly in plagiarism (no matter these assignments are from the original authors or from the plagiarists) will score ZERO marks. Further, disciplinary action will be followed.
Adequate in-program comments should be placed as appropriate. All user-defined names should be descriptive as much as possible. Marks are given based on correctness, programming quality, and style.
You are required to submit:
- Well-documented program listings and the executable results (screen dumps).
- Upload your files to Moodle including all your programs and report. It is required that your programs can be successfully compile.

View File

@@ -0,0 +1,15 @@
public class FoodOrder {
private int memberID;
private String foodOrder; // A, B, C, or D
private int priority;
//constructor
public FoodOrder(int memberID, String foodOrder) {
.......
}
//provide methods getter, setter, toString ....
}

View File

@@ -0,0 +1,119 @@
class ListNode {
private Object data;
private ListNode next;
public ListNode(Object o) { data = o; next = null; }
public ListNode(Object o, ListNode nextNode)
{ data = o; next = nextNode; }
public Object getData() { return data; }
public void setData(Object o) { data = o; }
public ListNode getNext() { return next; }
public void setNext(ListNode next) { this.next = next; }
} // class ListNode
class EmptyListException extends RuntimeException {
public EmptyListException ()
{ super("List is empty"); }
} // class EmptyListException
public class LinkedList {
private ListNode head;
private ListNode tail;
private int length; // the length of the list
public LinkedList() {
head = tail = null;
length = 0;
}
public boolean isEmpty() { return head == null; }
public void addToHead(Object item) {
if (isEmpty())
head = tail = new ListNode(item);
else
head = new ListNode(item, head);
length++;
}
public void addToTail(Object item) {
if (isEmpty())
head = tail = new ListNode(item);
else {
tail.setNext(new ListNode(item));
tail = tail.getNext();
}
length++;
}
public Object removeFromHead() throws EmptyListException {
Object item = null;
if (isEmpty())
throw new EmptyListException();
item = head.getData();
if (head == tail)
head = tail = null;
else
head = head.getNext();
length--;
return item;
}
public Object removeFromTail() throws EmptyListException {
Object item = null;
if (isEmpty())
throw new EmptyListException();
item = tail.getData();
if (head == tail)
head = tail = null;
else {
ListNode current = head;
while (current.getNext() != tail)
current = current.getNext();
tail = current;
current.setNext(null);
}
length--;
return item;
}
public int count() {
return length;
}
//students need to revise toString method
public String toString() {
String str = "[ ";
ListNode current = head;
while (current != null) {
str = str + current.getData() + " ";
current = current.getNext();
}
return str + " ]";
}
//to be completed ...
// Method remove(int) is to remove a ListNode from the LinkedList with a specific Member ID
public void remove(int targetID) throws EmptyListException {
.........
}
//to be completed ...
// Method add(Object) is to insert a new ListNode into the LinkedList in a correct position
public void add(Object item) {
.........
}
} // class LinkedList

View File

@@ -0,0 +1,25 @@
import ............
public class OrderSystem {
private static Scanner sc;
private static LinkedList orders;
private static int nextGuestID = 9000;
public static void main(String[] args) {
............
}
public static void inputOrder() throws ............ {
............
}
public static void adminFunc() ............ {
............
}
}

View File

@@ -0,0 +1,30 @@
public class CommissionWorker extends Worker{
private double commission;
private int quantity;
public CommissionWorker(String name, double c, int q) {
super(name);
setCommission(c);
setQuantity(q);
}
public void setCommission(double c) {
commission = c;
}
public void setQuantity(int q) {
quantity = q;
}
public double earnings() {
salary = commission * quantity;
return salary;
}
public String toString() {
return super.toString() + " earned commission of $" +
earnings();
}
}

View File

@@ -0,0 +1,30 @@
public class HourlyWorker extends Worker {
private double wage;
private double hours;
public HourlyWorker(String name, double w, double h) {
super(name);
setWage(w);
setHours(h);
}
public void setWage(double w) {
wage = w;
}
public void setHours(double h) {
hours = h;
}
public double earnings() {
salary = wage * hours;
return salary;
}
public String toString() {
return super.toString() + " earned $" + earnings() +
" for " + hours + " hours";
}
}

View File

@@ -0,0 +1,10 @@
public class TestWorker {
public static void main(String [] args) {
Worker [] w = new Worker[3];
w[0] = new Worker("Peter");
w[1] = new CommissionWorker("John", 120, 10);
w[2] = new HourlyWorker("Mary", 25, 40);
for( int i = 0; i < w.length; i++)
System.out.println(w[i]);
}
}

View File

@@ -0,0 +1,16 @@
public class Worker {
private String name;
protected double salary;
public Worker(String name) {
this.name = name;
}
public double earnings() {
return salary;
}
public String toString() {
return name;
}
}

View File

@@ -0,0 +1,22 @@
public class Coffee extends Drink {
protected boolean isSweet;
public Coffee(String name, int price, int volume, boolean isSweet) {
super(name, price, volume);
this.isSweet = isSweet;
}
public String toString() {
if (isSweet)
return super.toString() + ", sweet";
else
return super.toString() + ", not sweet";
}
public void setPrice(int price) {
if (price < 10)
this.price = 10;
else
super.setPrice(price);
}
}

View File

@@ -0,0 +1,19 @@
public class Drink extends Food {
protected int volume;
public Drink(String name, int price, int volume) {
super(name, price);
this.volume = volume;
}
public void setPrice(int price) {
if (price < 5)
this.price = 5;
else
this.price = price;
}
public String toString() {
return super.toString() + ", volume=" + volume;
}
}

View File

@@ -0,0 +1,25 @@
public class Food {
protected String name;
protected int price;
public Food() {
name = null;
price = 0;
}
public Food(String name, int price) {
this.name = name;
setPrice(price);
}
public String toString() {
return "name=" + name + ", price=" + price;
}
public void setPrice(int price) {
if (price >= 0)
this.price = price;
else
this.price = 0;
}
}

View File

@@ -0,0 +1,12 @@
public class TestFood {
public static void main(String s[]) {
Food f[] = new Food[4];
f[0] = new Drink("Pepsi", 7, 250);
f[1] = new Coffee("Cappuccino", 13, 200, true);
f[2] = new Drink("Orange Juice", -10, 180);
f[3] = new Coffee("Ireland", -11, 200, false);
for (int i = 0; i < f.length; i++) {
System.out.println("Food " + i + ": " + f[i]);
}
}
}

View File

@@ -0,0 +1,12 @@
public class Circle extends Shape { // line 10
private int radius; // line 11
public Circle(String name, int r) {
super(name); // line 12
radius = r; // line 13
}
public double area() {
return radius * radius * 3.1416;
}
}

View File

@@ -0,0 +1,9 @@
public abstract class Shape { // line 1
private String name; // line 2
public Shape(String name) { // line 3
this.name = name; // line 4
}
public abstract double area(); // line 5
}

View File

@@ -0,0 +1,12 @@
public class Square extends Shape { // line 6
private int side; // line 7
public Square(String name, int side) {
super(name); // line 8
this.side = side; // line 9
}
public double area() {
return side * side;
}
}

View File

@@ -0,0 +1,8 @@
public class TestShape {
public static void main(String[] args) { // line 14
Shape s1 = new Square("Square1", 4); // line 15
Shape s2 = new Circle("Circle1", 2); // line 16
System.out.println("Area of circle: " + s2.area()); // line 17
System.out.println("Area of square: " + s1.area()); // line 18
}
}

View File

@@ -0,0 +1,34 @@
public class Circle extends Shape{
private double radius;
private Point center;
public Circle(double radius, double x, double y){
super("circle");
this.radius = radius;
center = new Point(x, y);
}
public double getRadius(){
return radius;
}
public Point getCenter(){
return center;
}
public void setRadius(double radius){
this.radius = radius;
}
public void setCenter(Point center){
this.center = center;
}
public double getArea(){
return radius*radius*3.1416;
}
public String toString(){
return "center=" + center.toString() + "; radius=" + radius;
}
}

View File

@@ -0,0 +1,24 @@
public class Point {
private double x, y;
public Point(double a, double b) {
setPoint(a, b);
}
public void setPoint(double a, double b) {
x = a;
y = b;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public String toString() {
return "[" + x + ", " + y + "]";
}
}

View File

@@ -0,0 +1,40 @@
public class Rectangle extends Shape{
private Point topLeft;
private double width;
private double height;
public Rectangle(double width, double height, double x, double y) {
super("rectangle");
topLeft = new Point(x, y);
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
public Point getTopLeft() {
return topLeft;
}
public void setWidth(double width) {
this.width = width;
}
public void setHeight(double height) {
this.height = height;
}
public double getArea() {
return width * height;
}
public String toString() {
return "top left=" + topLeft.toString() + "; width=" + width + "; height=" + height;
}
}

View File

@@ -0,0 +1,13 @@
public abstract class Shape {
protected String name;
public Shape(String n) {
name = n;
}
public abstract double getArea();
public String getName() {
return name;
}
}

View File

@@ -0,0 +1,12 @@
public class TestShape {
public static void main(String[] args) {
Shape[] myShapes = new Shape[3];
myShapes[0] = new Circle(10.5, 20, 25);
myShapes[1] = new Rectangle(30.5, 23.5, 15.5, 20.5);
myShapes[2] = new Circle(8, 9.5, 10.5);
for (int i = 0; i < myShapes.length; i++) {
System.out
.println(myShapes[i].getName() + "=" + myShapes[i].toString() + "; Area=" + myShapes[i].getArea());
}
}
}

View File

@@ -0,0 +1,25 @@
public class PartTimeStaff extends Staff implements Salary {
private int workingHour;
public PartTimeStaff(String name, int id, char grade, int workingHour) {
super(name, id, grade);
this.workingHour = workingHour;
}
public void display() {
System.out.println("Name: " + name + "; ID: " + id + "; Grade: " + grade + "; Working Hour: " + workingHour + "; Salary: " + computeSalary());
}
public int computeSalary() {
switch (grade) {
case 'A':
return SALARY_A;
case 'B':
return SALARY_B;
case 'C':
return SALARY_C;
default:
return SALARY_OTHER;
}
}
}

View File

@@ -0,0 +1,8 @@
public interface Salary {
public final int SALARY_A = 4000;
public final int SALARY_B = 3000;
public final int SALARY_C = 2000;
public final int SALARY_OTHER = 1000;
public abstract int computeSalary();
}

View File

@@ -0,0 +1,13 @@
public abstract class Staff {
protected String name;
protected int id;
protected char grade;
public Staff(String name, int id, char grade) {
this.name = name;
this.id = id;
this.grade = grade;
}
public abstract void display();
}

View File

@@ -0,0 +1,8 @@
public class TestStaff {
public static void main(String args[]) {
PartTimeStaff p1 = new PartTimeStaff("John", 123, 'B', 20);
PartTimeStaff p2 = new PartTimeStaff("Mary", 124, 'A', 22);
p1.display();
p2.display();
}
}

View File

@@ -0,0 +1,16 @@
import java.util.Random;
public class Divide {
public static void main(String[] args) {
int a, n;
for (int i = 0; i < 10; i++) {
try{
n = (int) (Math.random() * 10);
a = 100 / n;
System.out.println("n:" + n + ", a:" + a);
}catch(ArithmeticException e){
System.out.println("Division by Zero");
}
}
}
}

View File

@@ -0,0 +1,21 @@
import java.util.*;
import java.io.*;
public class ReadTextFile {
public static void main(String[] args) {
String filename = "";
String line;
try {
filename = args[0];
Scanner fin = new Scanner(new File(filename));
while (fin.hasNextLine()) {
line = fin.nextLine();
System.out.println(line);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: java ReadTextFile <filename>");
} catch (FileNotFoundException e) {
System.out.println("Failed to open file " + filename);
}
}
}

View File

@@ -0,0 +1,17 @@
#### Question 1
| Exception class | IOException/ RuntimeException |
|--------------------------------|-------------------------------|
| ArithmeticException | RuntimeException |
| EOFException | IOException |
| FileNotFoundException | IOException |
| ArrayIndexOutOfBoundsException | RuntimeException |
| NumberFormatException | RuntimeException |
| InputMismatchException | RuntimeException |
| NUllPointerExpcetion | RuntimeExpcetion |
#### Question 2
(a) NullPointerException
(b) ArrayIndexOutOfBoundsException
(c) ArithmeticException(divide by zero)

View File

@@ -0,0 +1,50 @@
import javax.swing.JOptionPane;
public class InputParsing {
public static void main(String[] args) {
String input;
int num = 0;
int total = 0;
int average = 0;
int[] a = { 80, 60, 72, 85, 90 };
String output;
output = "The 5 marks are:";
for (int i = 0; i < 5; i++)
output += " " + a[i];
output += "\nAverage of how many numbers?";
input = JOptionPane.showInputDialog(output);
try {
System.out.println("Input length = " + input.length());
num = Integer.parseInt(input);
if (num == 0)
throw new ArithmeticException();
if (num == -1)
throw new NegativeNumberException();
total = 0;
for (int i = 0; i < num; i++)
total += a[i];
average = total / num;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No more than 5 please!");
} catch (NumberFormatException e) {
System.out.println("Integer please!");
} catch (NullPointerException e) {
System.out.println("Input length = 0; cancelled");
} catch (NegativeNumberException e) {
System.out.println(e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Don't input zero!");
} catch (RuntimeException e) {
System.out.println("Run time error!");
e.printStackTrace();
return;
} catch (Exception e) {
System.out.println("Something wrong!");
e.printStackTrace();
} finally {
System.out.println("Number = " + num);
}
System.out.println("Average over first " + num + " numbers = " + average);
}
}

View File

@@ -0,0 +1,66 @@
import javax.swing.JOptionPane;
public class InputParsing {
public static void main(String[] args) {
String input;
int[] a = { 80, 60, 72, 85, 90 };
String output;
output = "The 5 marks are:";
for (int i = 0; i < 5; i++)
output += " " + a[i];
output += "\nAverage of how many numbers?";
do {
input = JOptionPane.showInputDialog(output);
try {
parseInput(a, input);
} catch (Exception e) {
System.out.println("Number should be in 1 to 5!");
}
} while (JOptionPane.showConfirmDialog(null, "Enter again?", "elect an option",
JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION);
}
public static void parseInput(int[] a, String input) {
int num = 0;
int total = 0;
int average = 0;
try {
System.out.println("Input length = " + input.length());
num = Integer.parseInt(input);
if (num == 0)
throw new ArithmeticException();
if (num == -1)
throw new NegativeNumberException();
total = 0;
for (int i = 0; i < num; i++)
total += a[i];
average = total / num;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No more than 5 please!");
throw e;
} catch (NumberFormatException e) {
System.out.println("Integer please!");
} catch (NullPointerException e) {
System.out.println("Input length = 0; cancelled");
} catch (NegativeNumberException e) {
System.out.println(e.getMessage());
throw e;
} catch (ArithmeticException e) {
System.out.println("Don't input zero!");
throw e;
} catch (RuntimeException e) {
System.out.println("Run time error!");
e.printStackTrace();
return;
} catch (Exception e) {
System.out.println("Something wrong!");
e.printStackTrace();
} finally {
System.out.println("Number = " + num);
}
System.out.println("Average over first " + num + " numbers = " + average);
}
}

View File

@@ -0,0 +1,5 @@
public class NegativeNumberException extends ArithmeticException {
public NegativeNumberException() {
super("No negative number please!");
}
}

View File

@@ -0,0 +1,7 @@
{
"java.project.sourcePaths": ["src"],
"java.project.outputPath": "bin",
"java.project.referencedLibraries": [
"lib/**/*.jar"
]
}

View File

@@ -0,0 +1,18 @@
## Getting Started
Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code.
## Folder Structure
The workspace contains two folders by default, where:
- `src`: the folder to maintain sources
- `lib`: the folder to maintain dependencies
Meanwhile, the compiled output files will be generated in the `bin` folder by default.
> If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there.
## Dependency Management
The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies).

View File

@@ -0,0 +1,7 @@
public interface Comparator {
public abstract boolean isEqualTo(Object item1, Object item2);
public abstract boolean isLessThan(Object item1, Object item2);
public abstract boolean isLessThanOrEqualTo(Object item1, Object item2);
public abstract boolean isGreaterThan(Object item1, Object item2);
public abstract boolean isGreaterThanOrEqualTo(Object item1, Object item2);
}

View File

@@ -0,0 +1,54 @@
public class ComparatorLinkedList extends LinkedList {
Comparator comparator;
ComparatorLinkedList(Comparator comparator) {
super();
this.comparator = comparator;
}
public void removeItem(Object item) throws ItemNotFoundException, EmptyListException {
if (isEmpty()) {
throw new ItemNotFoundException();
}
if (comparator.isEqualTo(head.data, item)) {
removeFromHead();
} else if (comparator.isEqualTo(tail.data, item)) {
removeFromTail();
} else {
ListNode current = head;
while (current.next != null) {
if (comparator.isEqualTo(current.next.data, item)) {
current.next = current.next.next;
return;
}
current = current.next;
}
throw new EmptyListException();
}
}
public void insertInOrder(Object item) {
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
if (comparator.isGreaterThanOrEqualTo(head.data, item)) {
addToHead(item);
} else if (comparator.isLessThanOrEqualTo(tail.data, item)) {
addToTail(item);
} else {
ListNode current = head;
while (current.next != null) {
if (comparator.isGreaterThanOrEqualTo(current.next.data, item)) {
ListNode newNode = new ListNode(item);
newNode.next = current.next;
current.next = newNode;
return;
}
current = current.next;
}
}
}
}
}

View File

@@ -0,0 +1,80 @@
public class DoublyList {
private DoublyNode head;
private DoublyNode tail;
public DoublyList() {
head = tail = null;
}
public boolean isEmpty() {
return (head == null);
}
public void addToHead(Object item) {
if (isEmpty()) {
head = tail = new DoublyNode(item);
} else {
head.previous = new DoublyNode(item, null, head);
head = head.previous;
}
}
public void addToTail(Object item) {
if (isEmpty()) {
head = tail = new DoublyNode(item);
} else {
tail.next = new DoublyNode(item, tail, null);
tail = tail.next;
}
}
public Object removeFromHead() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
Object item = head.data;
if (head == tail) {
head = tail = null;
} else {
head = head.next;
head.previous = null;
}
return item;
}
public Object removeFromTail() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
Object item = tail.data;
if (head == tail) {
head = tail = null;
} else {
tail = tail.previous;
tail.next = null;
}
return item;
}
public String toString(){
String s ="[";
DoublyNode current = head;
while(current!=null){
s+=current.data + " ";
current = current.next;
}
return s + "]";
}
public String forward(){
return toString();
}
public String backward(){
String s = "[";
DoublyNode current =tail;
while(current != null){
s+= current.data + " ";
current = current.previous;
}
return s+ "]";
}
}

View File

@@ -0,0 +1,19 @@
public class DoublyNode {
Object data;
DoublyNode previous;
DoublyNode next;
DoublyNode(Object data){
this.data = data;
previous = next = null;
}
DoublyNode(Object data, DoublyNode previous, DoublyNode next){
this.data = data;
this.previous = previous;
this.next = next;
}
}

View File

@@ -0,0 +1,5 @@
public class EmptyListException extends Exception{
EmptyListException(){
super();
}
}

View File

@@ -0,0 +1,7 @@
public class ItemNotFoundException extends Exception {
ItemNotFoundException(){
super();
}
}

View File

@@ -0,0 +1,158 @@
public class LinkedList {
ListNode head;
ListNode tail;
int count = 0;
LinkedList(){
head = null;
tail = null;
}
public int getCount(){
return count;
}
public boolean isEmpty(){
return (head == null && tail == null);
}
public void addToHead(Object data){
ListNode node = new ListNode(data);
if(isEmpty()){
head = tail = node;
count++;
return;
}
node.next = head;
head = node;
count++;
}
public void addToTail(Object data){
ListNode node = new ListNode(data);
if(isEmpty()){
head = tail = node;
count++;
return;
}
tail.next = node;
tail = node;
count++;
}
public Object removeFromHead(){
if(isEmpty())
throw new IndexOutOfBoundsException();
ListNode node = head;
if(tail == head){
head = tail = null;
count--;
return node.data;
}
head = head.next;
count--;
return node.data;
}
public Object removeFromTail(){
if(isEmpty())
throw new IndexOutOfBoundsException();
ListNode node = tail;
if(tail == head){
head = tail = null;
count--;
return node.data;
}
ListNode currentNode = head;
while(currentNode.next != tail){
currentNode = currentNode.next;
System.out.println(currentNode.data);
}
currentNode.next = null;
tail = currentNode;
count--;
return node.data;
}
public String toString(){
ListNode currentNode = head;
String listData = "";
while (currentNode != null){
listData += currentNode.data + " ";
currentNode = currentNode.next;
}
return listData;
}
public void clear(){
head = tail = null;
}
public Object getItemAt(int n){
if (n < 0 || n >= count)
throw new IndexOutOfBoundsException();
int currentPos = 0;
ListNode currentNode = head;
while(currentPos < n){
if(count == currentPos)
break;
currentNode = currentNode.next;
currentPos++;
}
return currentNode.data;
}
public Object removeItemAt(int n){
if (n < 0 || n >= count)
throw new IndexOutOfBoundsException();
int currentPos = 0;
ListNode currentNode = head;
if(n==0){
removeFromHead();
return currentNode.data;
}
while(currentPos < n-1){
currentNode = currentNode.next;
currentPos++;
}
ListNode item = currentNode.next;
currentNode.next = currentNode.next.next;
count--;
return item.data;
}
public void addItemAt(Object item, int n){
if (n > count)
throw new IndexOutOfBoundsException();
if (isEmpty() || n == 0){
addToHead(item);
return;
}
ListNode node = new ListNode(item);
int currentPos = 0;
ListNode currentNode = head;
while(currentPos < n-1){
currentNode = currentNode.next;
currentPos++;
}
node.next = currentNode.next;
currentNode.next = node;
count++;
}
}

View File

@@ -0,0 +1,14 @@
public class ListNode {
Object data;
ListNode next;
ListNode(Object data, ListNode next){
this.data = data;
this.next = next;
}
ListNode(Object data){
this.data = data;
this.next = null;
}
}

View File

@@ -0,0 +1,17 @@
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String toString() {
return "(" + name + ", " + age + ")";
}
}

View File

@@ -0,0 +1,28 @@
public class PersonComparator implements Comparator {
public boolean isEqualTo(Object item1, Object item2) {
return (((Person) item1).getAge()==((Person) item2).getAge());
}
public boolean isLessThan(Object item1, Object item2) {
return (((Person) item1).getAge()<((Person) item2).getAge());
}
public boolean isLessThanOrEqualTo(Object item1, Object item2) {
return(isLessThan(item1, item2) || isEqualTo(item1, item2));
}
public boolean isGreaterThan(Object item1, Object item2) {
return (((Person) item1).getAge()>((Person) item2).getAge());
}
public boolean isGreaterThanOrEqualTo(Object item1, Object item2) {
return (isGreaterThan(item1, item2) || isEqualTo(item1, item2));
}
}

View File

@@ -0,0 +1,22 @@
public class StringComparator implements Comparator{
public boolean isEqualTo(Object item1, Object item2) {
return ((String) item1).compareTo((String) item2) == 0;
}
public boolean isLessThan(Object item1, Object item2) {
return((String) item1).compareTo((String) item2) < 0;
}
public boolean isLessThanOrEqualTo(Object item1, Object item2) {
return (isEqualTo(item1, item2) || isLessThan(item1, item2));
}
public boolean isGreaterThan(Object item1, Object item2) {
return (((String) item1).compareTo((String) item2) > 0);
}
public boolean isGreaterThanOrEqualTo(Object item1, Object item2) {
return (isEqualTo(item1, item2) || isGreaterThan(item1, item2));
}
}

View File

@@ -0,0 +1,45 @@
public class Test {
public static void main(String[] args) {
LinkedList s = new LinkedList();
System.out.println(s);
s.addToHead("Betty");
s.addToTail("Dave");
s.addToTail("Felix");
s.addToTail("Jenny");
System.out.println(s);
System.out.println("count = " + s.getCount());
System.out.println("Pos 0 = " + s.getItemAt(0));
System.out.println("Pos 2 = " + s.getItemAt(2));
System.out.println("Last = " + s.getItemAt(s.getCount() - 1));
s.addItemAt("Gary", 3);
System.out.println(s);
s.addItemAt("Apple", 0);
System.out.println(s);
System.out.println("Removing " + s.removeItemAt(2));
System.out.println(s);
System.out.println("Removing " + s.removeItemAt(0));
System.out.println(s);
System.out.println("Removing " + s.removeItemAt(3));
System.out.println(s);
// Comparator c = new StringComparator();
// ComparatorLinkedList s = new ComparatorLinkedList(c);
// System.out.println(s);
// s.insertInOrder("Betty");
// System.out.println(s);
// s.insertInOrder("Dave");
// System.out.println(s);
// s.insertInOrder("Catherine");
// System.out.println(s);
// s.insertInOrder("Thomas-1");
// System.out.println(s);
// s.insertInOrder("Sandra");
// System.out.println(s);
// s.insertInOrder("Thomas-2");
// System.out.println(s);
// s.insertInOrder("Alice-1");
// System.out.println(s);
// s.insertInOrder("Alice-2");
// System.out.println(s);
}
}

View File

@@ -0,0 +1,25 @@
public class TestDoubkyList {
public static void main(String[] args) throws EmptyListException {
DoublyList s = new DoublyList();
System.out.println(s);
s.addToTail(1);
System.out.println(s);
s.addToTail(2);
System.out.println(s);
s.addToTail(3);
System.out.println(s);
s.addToHead(0);
System.out.println(s.forward());
System.out.println(s.backward());
while (!s.isEmpty()) {
System.out.println("removed: " + s.removeFromHead());
System.out.println(s);
}
}
}

View File

@@ -0,0 +1,189 @@
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestLinkedList {
private LinkedList list;
@Before
public void init(){
list = new LinkedList();
}
@After
public void teardown(){
list.clear();
}
@Test
public void testAddToHead1(){
list.addToHead("1");
assertEquals(list.toString().trim(), "1");
assertEquals(list.count, 1);
}
@Test
public void testAddToHead2(){
list.addToHead("3");
list.addToHead("2");
list.addToHead("1");
assertEquals(list.toString().trim(), "1 2 3");
}
@Test
public void testAddToTail1(){
list.addToTail("1");
list.addToTail("2");
list.addToTail("3");
assertEquals(list.toString().trim(), "1 2 3");
}
@Test
public void testAddToTail2(){
list.addToTail("1");
assertEquals(list.toString().trim(), "1");
assertEquals(list.count, 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRemoveFromTail1(){
list.removeFromTail();
}
@Test
public void testRemoveFromTail2(){
list.addToTail(1);
list.removeFromTail();
assertEquals(list.count, 0);
assertEquals(list.toString().trim(), "");
}
@Test
public void testRemoveFromTail3(){
list.addToTail("1");
list.addToTail("2");
list.addToTail("3");
list.addToTail("4");
list.addToHead("0");
list.removeFromTail();
Object data = list.removeFromTail();
assertEquals(data.toString(), "3");
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRemoveFromHead1() {
list.removeFromHead();
}
@Test
public void testRemoveFromHead2() {
list.addToHead("3");
list.addToHead("2");
list.addToHead("1");
list.addToHead("0");
Object data = list.removeFromHead();
assertEquals(data.toString(), "0");
}
@Test
public void testRemoveFromHead3(){
list.addToTail("1");
list.addToHead("0");
list.addToTail("2");
list.removeFromHead();
list.removeFromHead();
list.removeFromHead();
assertEquals(list.toString().trim(), "");
}
@Test(expected = IndexOutOfBoundsException.class)
public void testGetItemAt1(){
list.getItemAt(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testGetItemAt2(){
list.getItemAt(1);
}
@Test
public void testGetItemAt3(){
list.addToTail(1);
assertEquals(list.getItemAt(0), 1);
}
@Test
public void testGetItemAt4(){
list.addToTail(1);
list.addToTail(2);
list.addToTail(3);
list.addToTail(4);
list.removeFromTail();
assertEquals(list.getItemAt(2), 3);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRemoveItemAt1(){
list.removeItemAt(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRemoveItemAt2(){
list.removeItemAt(1);
}
@Test
public void testRemoveItemAt3(){
list.addToTail(1);
assertEquals(list.removeItemAt(0), 1);
assertEquals(list.count, 0);
}
@Test
public void testRemoveItemAt4(){
list.addToTail(1);
list.addToTail(2);
list.addToTail(3);
list.addToTail(4);
assertEquals(list.removeItemAt(2), 3);
assertEquals(list.count, 3);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testAddItemAt1(){
System.out.println(list.count);
list.addItemAt(1, 1);
}
@Test
public void testAddItemAt2(){
list.addItemAt(1, 0);
assertEquals(list.count, 1);
assertEquals(list.toString().trim(), "1");
}
@Test
public void testAddItemAt3(){
list.addItemAt(2, 0);
list.addItemAt(1, 0);
assertEquals(list.count, 2);
assertEquals(list.toString().trim(), "1 2");
}
@Test
public void testAddItemAt4(){
list.addToTail(1);
list.addItemAt(2, 1);
list.addItemAt(3, 2);
list.addItemAt(4, 3);
assertEquals(list.count, 4);
assertEquals(list.toString().trim(), "1 2 3 4");
}
}

View File

@@ -0,0 +1,19 @@
public class TestPerson {
public static void main(String[] args) throws ItemNotFoundException, EmptyListException {
Comparator c = new PersonComparator();
ComparatorLinkedList s = new ComparatorLinkedList(c);
System.out.println(s);
s.insertInOrder(new Person("Betty", 21));
System.out.println(s);
s.insertInOrder(new Person("Sandra", 19));
System.out.println(s);
s.insertInOrder(new Person("Alice", 32));
System.out.println(s);
s.insertInOrder(new Person("John", 15));
System.out.println(s);
s.insertInOrder(new Person("Kenneth", 19));
System.out.println(s);
s.removeItem(new Person("unknown", 15));
System.out.println(s);
}
}

View File

@@ -0,0 +1,47 @@
public class ArrayStack implements Stack {
public static final int CAPACITY =1000;
private int capacity;
private Object[] array;
private int top =-1;
public ArrayStack() {
this(CAPACITY);
}
public ArrayStack(int cap){
capacity =cap;
array = new Object[capacity];
}
@Override
public int size() {
return top+1;
}
@Override
public boolean isEmpty() {
return (top<0);
}
@Override
public void push(Object item) throws StackFullException {
if(size()==capacity)
throw new StackFullException();
array[++top]=item;
}
@Override
public Object pop() throws StackEmptyException {
if(isEmpty())
throw new StackEmptyException();
Object item =array[top];
array[top--]=null;
return item;
}
@Override
public Object top() throws StackEmptyException {
if(isEmpty())
throw new StackEmptyException ();
return array[top];
}
}

View File

@@ -0,0 +1,6 @@
class EmptyListException extends Exception {
public EmptyListException() {
}
}

View File

@@ -0,0 +1,101 @@
import java.util.Scanner;
public class EvaPostfix {
public static void main(String[] args) {
Stack s = new LinkedStack();
Scanner keyboard = new Scanner(System.in);
System.out.print("Input the infix expression? ");
String exp = keyboard.nextLine();
try {
if (parenthesisMatching(exp)) {
for (int i = 0; i < exp.length(); i++) {
char item = exp.charAt(i);
if (item == '(' || item == '{' || item == '[') {
s.push(item);
} else if (isOperater(item)) {
if (s.isEmpty()) {
s.push(item);
} else if ((checkVal(item) == checkVal((char) s.top())) || (checkVal(item) < checkVal((char) s.top()))) {
System.out.print(s.pop());
if(s.isEmpty()){
s.push(item);
}else if(checkVal((char) s.top()) == checkVal(item)) {
while (checkVal(item) == checkVal((char) s.top())) {
System.out.print(s.pop());
if (s.isEmpty()) {
s.push(item);
break;
}
}
} else {
s.push(item);
}
} else if (checkVal(item) > checkVal((char) s.top())) {
s.push(item);
}
} else if (item == ')' || item == ']' || item == '}') {
while (((char) s.top() != '(')&&((char) s.top() != '{') && ((char) s.top() != '[')) {
System.out.print(s.pop());
}
s.pop();
} else {
System.out.print(item);
}
}
while (!s.isEmpty()) {
System.out.print(s.pop());
}
} else {
System.out.println("Error");
}
} catch (StackEmptyException e) {
System.out.println("Parenthesis not matched");
} catch (StackFullException e) {
System.out.println("Parenthesis not matched");
}
}
public static boolean parenthesisMatching(String exp) throws StackFullException, StackEmptyException {
Stack s = new LinkedStack();
char item;
for (int i = 0; i < exp.length(); i++) {
item = exp.charAt(i);
if (item == '{' || item == '(' || item == '[') {
s.push(item);
} else if (item == '}' || item == ')' || item == ']') {
char x = (char) s.pop();
if ((x != '(') && (x != '[') && (x != '{')) {
return false;
}
}
}
if (s.isEmpty()) {
return true;
} else {
return false;
}
}
public static boolean isOperater(char exp) {
switch (exp) {
case '+':
case '-':
case '*':
case '/':
return true;
default:
return false;
}
}
public static int checkVal(char exp) {
if (exp == '*' || exp == '/') {
return 5;
} else if (exp == '+' || exp == '-') {
return 3;
} else {//'('
return -1;
}
}
}

View File

@@ -0,0 +1,132 @@
public class LinkedList {
private ListNode head;
private ListNode tail;
private int count = 0;
public boolean isEmpty() {
return (head == null);
}
public void addToHead(Object item) {
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
head = new ListNode(item, head);
}
count++;
}
public void addToTail(Object item) {
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
tail.next = new ListNode(item);
tail = tail.next;
}
count++;
}
public Object removeFromHead() throws EmptyListException {
Object item = null;
if (isEmpty()) {
throw new EmptyListException();
}
item = head.data;
if (head == tail) {
head = tail = null;
} else {
head = head.next;
}
count--;
return item;
}
public Object removeFromtail() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
Object item = tail.data;
if (head == tail) {
head = tail = null;
return item;
}
ListNode current = head;
while (current.next != tail) {
current = current.next;
}
tail = current;
tail.next = null;
count--;
return item;
}
public String toString() {
String s = "[ ";
ListNode current = head;
while (current != null) {
s = s + current.data + " ";
current = current.next;
}
return s + " ]";
}
public int getCount() {
return count;
}
public Object getItemAt(int n) {
if (n < 0 || n >= count) {
throw new IndexOutOfBoundsException();
}
int currentPos = 0;
ListNode current = head;
while (currentPos <= (n - 1)) {
current = current.next;
currentPos++;
}
return current.data;
}
public void addItemAt(Object item, int n) {
if (isEmpty() || n == 0) {
addToHead(item);
return;
}
if (n >= count) {
addToTail(item);
return;
}
int currentPos = 0;
ListNode current = head;
while (currentPos < (n - 1)) {
current = current.next;
currentPos++;
}
ListNode newNode = new ListNode(item);
newNode.next = current.next;
current.next = newNode;
count++;
}
public Object removeItemAt(int n) throws EmptyListException{
if(n<0 || n>=count)
throw new IndexOutOfBoundsException();
if(n==0)
removeFromHead();
int currentPos=0;
ListNode current=head;
while(currentPos<(n-1)){
current = current.next;
currentPos++;
}
Object item = current.next.data;
current.next = current.next.next;
count--;
return item;
}
}

View File

@@ -0,0 +1,39 @@
public class LinkedStack implements Stack {
private LinkedList sll = new LinkedList();
@Override
public int size() {
return sll.getCount();
}
@Override
public boolean isEmpty() {
return sll.isEmpty();
}
@Override
public void push(Object item) throws StackFullException {
sll.addToHead(item);
}
@Override
public Object pop() throws StackEmptyException {
try {
Object item = sll.removeFromHead();
return item;
} catch (EmptyListException e) {
throw new StackEmptyException();
}
}
@Override
public Object top() throws StackEmptyException {
try {
Object item = sll.removeFromHead();
sll.addToHead(item);
return item;
} catch (EmptyListException e) {
throw new StackEmptyException();
}
}
}

View File

@@ -0,0 +1,13 @@
public class ListNode {
public Object data;
public ListNode next;
public ListNode(Object ListNode){
this.data = ListNode;
this.next = null;
}
public ListNode(Object ListNode, ListNode next){
this.data = ListNode;
this.next = next;
}
}

View File

@@ -0,0 +1,44 @@
import java.util.Scanner;
public class ParenthesisMatching {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Expression? ");
String exp = keyboard.nextLine();
try {
if (parenthesisMatching(exp)) {
System.out.println("Parenthes is matched");
} else {
System.out.println("Parenthesis not matched");
}
} catch (StackEmptyException e) {
System.out.println("Parenthesis not matched");
} catch (StackFullException e) {
System.out.println("Parenthesis not matched");
}
keyboard.close();
}
public static boolean parenthesisMatching(String exp) throws StackFullException, StackEmptyException {
Stack s = new LinkedStack();
char item;
for (int i = 0; i < exp.length(); i++) {
item = exp.charAt(i);
if (item == '{' || item == '(' || item == '[') {
s.push(item);
} else if (item == '}' || item == ')' || item == ']') {
char x = (char) s.pop();
if ((x != '(') && (x != '[') && (x != '{')) {
return false;
}
}
}
if (s.isEmpty()) {
return true;
} else {
return false;
}
}
}

View File

@@ -0,0 +1,16 @@
public class Reverse {
public static void main(String [ ] args) throws StackFullException, StackEmptyException {
String [ ] arr = {"Abby", "Boris", "Cat", "Dino", "Elvis"};
Stack stack = new ArrayStack();
for (int i=0; i<arr.length; i++) {
stack.push(arr[i]);
}
for (int i=0; i<arr.length; i++) {
arr[i] = (String) stack.pop();
}
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}

View File

@@ -0,0 +1,7 @@
public interface Stack {
public abstract int size();
public abstract boolean isEmpty();
public abstract void push(Object item) throws StackFullException;
public abstract Object pop() throws StackEmptyException;
public abstract Object top() throws StackEmptyException;
}

View File

@@ -0,0 +1,3 @@
public class StackEmptyException extends Exception {
}

View File

@@ -0,0 +1,3 @@
public class StackFullException extends Exception {
}

View File

@@ -0,0 +1,59 @@
public class ArrayQueue {
public static final int CAPACITY = 1000;
private int capacity;
private Object[] array;
private int front = 0;
private int rear = 0;
public ArrayQueue() {
this(CAPACITY);
}
public ArrayQueue(int cap) {
capacity = cap;
array = new Object[capacity];
}
public int size() {
return (capacity - front + rear) % capacity;
}
public boolean isEmpty() {
return (front == rear);
}
public void enqueue(Object item) throws QueueFullException {
if (size() == capacity - 1) {
throw new QueueFullException();
}
array[rear] = item;
rear = (rear + 1) % capacity;
}
public Object dequeue() throws QueueEmptyException {
if (isEmpty()) {
throw new QueueEmptyException();
}
Object item = array[front];
array[front] = null;
front = (front + 1) % capacity;
return item;
}
public Object front() throws QueueEmptyException {
if (isEmpty()) {
throw new QueueEmptyException();
}
return array[front];
}
public String toString() {
String s = "[ ";
int next = front;
for (int i = 0; i < size(); i++) {
s += array[next] + " ";
next = front + i;
}
return s + " ]";
}
}

View File

@@ -0,0 +1,5 @@
public class EmptyListException extends RuntimeException {
public EmptyListException() {
super("List is empty.");
}
}

View File

@@ -0,0 +1,88 @@
public class LinkedList {
private ListNode head;
private ListNode tail;
private int count;
public LinkedList() {
head = null;
tail = null;
count = 0;
}
public boolean isEmpty() {
return (head==null);
}
public int getCount() {
return count;
}
public void addToHead(Object item) {
count++;
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
head = new ListNode(item, head);
}
}
public void addToTail(Object item) {
count++;
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
tail.next = new ListNode(item);
tail = tail.next;
}
}
public Object removeFromHead() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
Object item = head.data;
if (head == tail) // there's only one single node
head = tail = null;
else
head = head.next;
count--;
return item;
}
public Object removeFromTail() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
count--;
Object item = tail.data;
if (head == tail) { // there is only one node
head = tail = null;
return item;
}
// search for the second last node
ListNode current = head;
while (current.next != tail)
current = current.next;
// set second last node as new tail
tail = current;
tail.next = null;
return item;
}
public String toString() {
String s = "[ ";
// traverse the list from head towards tail
ListNode current = head;
while (current != null) {
s += current.data + " ";
current = current.next;
}
return s + "]";
}
}

View File

@@ -0,0 +1,42 @@
public class LinkedQueue {
LinkedList qll;
public LinkedQueue() {
qll = new LinkedList();
}
public int size() {
return qll.getCount();
}
public boolean isEmpty() {
return qll.isEmpty();
}
public void enqueue(Object item) throws QueueFullException {
qll.addToTail(item);
}
public Object dequeue() throws QueueEmptyException {
try {
Object item = qll.removeFromHead();
return item;
} catch (EmptyListException e) {
throw new QueueEmptyException();
}
}
public String toString() {
return qll.toString();
}
public Object front() throws QueueEmptyException {
try {
Object item = qll.removeFromHead();
qll.addToHead(item);
return item;
} catch (EmptyListException e) {
throw new QueueEmptyException();
}
}
}

View File

@@ -0,0 +1,17 @@
public class ListNode {
public Object data; // set to public for implementation convenience
public ListNode next;
public ListNode(Object data) {
this.data = data;
this.next = null;
}
public ListNode(Object data, ListNode next) {
this.data = data;
this.next = next;
}
}

View File

@@ -0,0 +1,7 @@
public interface Queue {
public abstract boolean isEmpty();
public abstract int size();
public abstract Object front() throws QueueEmptyException;
public abstract void enqueue(Object item) throws QueueFullException;
public abstract Object dequeue() throws QueueEmptyException;
}

View File

@@ -0,0 +1,5 @@
public class QueueEmptyException extends Exception{
}

View File

@@ -0,0 +1,5 @@
public class QueueFullException extends Exception{
}

View File

@@ -0,0 +1,17 @@
### Q3
In topic “3.1 Linked Lists”, we have discussed the importance of using a tail for referencing the last node in a linked list. The purpose of this exercise is to have an empirical study on the impact of using the tail reference on a linked list.
Execute the program multiple times with different value for <num>. Record the execution
time as reported by the program in a spreadsheet.
(b) Copy your programs in Q3(a) to a new folder. Q3(b). Modify the Java program LinkedList.java so that the linked list does not contain the tail reference. Needless to say, when the last node in the linked list is wanted, you need to traverse the list from the head towards its end until the last node is reached. Execute LinkedQueueTiming again using the same set of <num> values as in Q3(a). Record the execution time as reported by the program in the spreadsheet.
| n | num | with tail Q3(a) | average time(with tail) | waithout tail Q3(b) | average time(without tail) |
| --- | --- | --- | --- | --- | --- |
| 1 | 10 | 266800 | 276500 | 272300 | 294200 |
| 2 | 100 | 281600 | 288650 | 325500 | 345600 |
| 3 | 1000| 669900 | 671020 | 1767600 | 1678600 |
| 4 | 10000 | 1575200 | 1595300 | 90549600 | 101132100 |
| 5 | 100000 | 5840900 | 6020100 | 9229402000 | 9103203100 |
| 6 | 1000000 | 24357800 | 26236800 | 1500203112900 | 1612141023950 |

View File

@@ -0,0 +1,32 @@
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BstTiming {
public static void main(String[] args) {
try {
StringBst tree = new StringBst();
Scanner fin = new Scanner(new File(args[0]));
String line;
while (fin.hasNextLine()) {
line = fin.nextLine();
line = line.trim();
tree.addNode(line);
}
fin.close();
long startTime = System.nanoTime();
String ans = tree.search(args[1]);
long endTime = System.nanoTime();
if (ans==null)
System.out.println("Not found; Time used: " + (endTime - startTime));
else
System.out.println("Found; Time used: " + (endTime - startTime));
}
catch (FileNotFoundException e) {
System.out.println("Failed to open " + args[0]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: BstTiming <word_file> <search_word>");
}
}
}

View File

@@ -0,0 +1,240 @@
### Q2(c)
Now, perform some experiments to test the searching performance in the two approaches. Record the results in the table below. You are free to try some more words.
| Word to search for | Result (found/ not found) | Time needed (BST) | Time needed (linked list)
| --- | --- | --- | --- |
| water | Found | 2500 | 7100 |
| ever | Found | 4800 | 77600 |
| snail | Not Found | 4500 | 74200 |
| better | Not Found | 3900 | 80700 |
| apple | Found | 5700 | 49700 |
| door | Found | 3300 | 7300 |
| foolish | Found | 4000 | 52000 |
### Q4
A proper binary tree contains N nodes. What is the number of leaf nodes in the tree? What is the
number of non-leaf nodes in the tree?
```
Leaf nodes = N/2+1 (N must be an odd number, so take the integer of N/2.)
Non-leaf nodes = N/2
```
### Q5
A complete binary tree has a depth of 8. What is the total number of nodes in the tree? Give the
relationship of the depth and the total number of nodes of a complete binary tree in a mathematic
expression.
```
Total nodes = 2^(8+1) 1 = 511
```
### Q6a
Draw the array of the binary tree if it is implemented in an
array.
```
[Q]
/ \
[B] [U]
\ / \
[G] [R][W]
/ \
[E] [J]
\ / \
[F] [I] [P]
/
[H]
```
```
0:Q 1:B 2:U 4:G 5:R 6:W 9:E 10:J 20:F 21:I 22:P 43:H
```
### Q6(b)
(b)List the node sequence by
(i) pre-order traversal
```
Q B G E F J I H P U R W
```
(ii) in-order traversal
```
B E F G H I J P Q R U W
```
(iii) post-order traversal
```
F E H I P J G B R W U Q
```
### Q7
Follow the algorithm outlined in the lecture notes, depict the Binary Search Trees created by inserting the items below from left to right. Perform an in-order traversal to check if the nodes are visited in ascending order.
(a) M J W S G L K A B P Z X Y R T
```
M
/ \
/ \
/ \
/ \
J W
/ \ / \
G L / \
/ / / \
A K S Z
\ / \ /
B / \ X
P T \
\ Y
R
```
(b) P W J Y B L S G K M A Z X T R
```
P
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
J W
/ \ / \
/ \ / \
/ \ / \
B L / \
/ \ / \ S Y
A G / \ / \ / \
K M / \ / \
R T X Z
```
(c) P W J Y B L S G K M A R
```
P
/ \
/ \
/ \
/ \
/ \
J W
/ \ / \
/ \ S Y
/ \ /
B L R
/ \ / \
A G / \
K M
```
(d) P W J Y B L S G K M A
```
P
/ \
/ \
/ \
/ \
/ \
J W
/ \ / \
/ \ S Y
/ \
B L
/ \ / \
A G / \
K M
```
(e) A B C D E F G H I J K L
```
A
\
B
\
C
\
D
\
E
\
F
\
G
\
H
\
I
\
J
\
K
\
L
```
(f) L K J I H G F E D C B A
```
L
/
K
/
J
/
I
/
H
/
G
/
F
/
E
/
D
/
C
/
B
/
A
```
### Q8
Outline an algorithm of searching an item in a Binary Search Tree.
```
BinaryNode search (BinaryNode t, key x)
begin
if t is null
return null;
if (x is less than t.data.key)
return search(t.left, x);
else if (x is greater than t.data.key)
return search(t.right, x);
else
return t;
end
```
### Q10
Give the postfix and prefix expressions as well as the expression tree.
((A + B) * C) / (D + E) * F
```
[*]
/ \
[/] [F]
/ \
/ \
/ \
[*] [+]
/ \ / \
[+] [C] [D] [E]
/ \
/ \
[A] [B]
pre-order traversal on the expression tree to yields the prefix expression
Prefix expression: * / * + A B C + D E F
```

View File

@@ -0,0 +1,89 @@
public class StringBst {
private StringBstNode root;
public StringBst() {
root = null;
}
public void addNode(String data) {
StringBstNode p = root, prev = null;
if (root == null) {
root = new StringBstNode(data);
return;
}
while (p != null) {
prev = p;
if (data.compareTo(p.getData()) < 0) {
p = p.getLeft();
} else {
p = p.getRight();
}
}
if (data.compareTo(prev.getData()) < 0) {
prev.setLeft(new StringBstNode(data));
} else {
prev.setRight(new StringBstNode(data));
}
}
public String search(String data) {
StringBstNode p = root;
if (root == null) {
return null;
}
while (p!=null) {
if (data.compareTo(p.getData()) < 0) {
p = p.getLeft();
} else if(data.compareTo(p.getData()) > 0){
p = p.getRight();
}
else{
return p.getData();
}
}
return null;
}
public void preorder() {
preorder(root);
}
public void preorder(StringBstNode v) {
System.out.print(v.getData() + " ");
if (v.getLeft() != null) {
preorder(v.getLeft());
}
if (v.getRight() != null) {
preorder(v.getRight());
}
}
public void inorder() {
inorder(root);
}
public void inorder(StringBstNode v) {
if (v.getLeft() != null) {
inorder(v.getLeft());
}
System.out.print(v.getData() + " ");
if (v.getRight() != null) {
inorder(v.getRight());
}
}
public void postorder() {
postorder(root);
}
public void postorder(StringBstNode v) {
if (v.getLeft() != null) {
postorder(v.getLeft());
}
if (v.getRight() != null) {
postorder(v.getRight());
}
System.out.print(v.getData() + " ");
}
}

View File

@@ -0,0 +1,32 @@
public class StringBstNode {
private String data;
private StringBstNode left;
private StringBstNode right;
public StringBstNode(String data) {
this.data = data;
this.left = null;
this.right = null;
}
public String getData() {
return data;
}
public StringBstNode getLeft() {
return left;
}
public StringBstNode getRight() {
return right;
}
public void setLeft(StringBstNode p) {
left = p;
}
public void setRight(StringBstNode p){
right =p;
}
}

View File

@@ -0,0 +1,853 @@
water
button
door
able
circle
near
comfort
sock
open
only
road
addition
plough
science
level
expansion
ear
education
insurance
shake
fixed
bone
card
laugh
winter
burst
answer
physical
sense
get
clear
thumb
island
eye
ornament
gold
again
old
point
purpose
plate
distance
drop
daughter
VTC
range
silk
rain
brown
interest
business
skin
condition
danger
paste
boy
adjustment
polish
time
net
jump
fight
stomach
talk
white
animal
neck
no
garden
list
star
drink
chest
tin
feeble
direction
and
land
warm
than
digestion
manager
match
mixed
moon
quiet
tray
jelly
transport
chin
wait
hand
opinion
use
join
cook
potato
cloud
heart
debt
stop
snake
complex
fowl
mind
month
arch
growth
care
plane
argument
about
say
because
ship
colour
responsible
elastic
flag
error
front
hear
wax
ray
coal
unit
suggestion
well
news
trousers
surprise
prison
bread
beautiful
death
wound
harmony
mine
river
opposite
off
this
ant
history
cough
watch
observation
move
not
balance
cry
relation
pull
if
clean
cover
breath
weather
comb
that
trouble
smash
root
voice
sail
disease
important
cup
look
belief
give
hate
over
forward
basket
soap
before
oven
coat
have
exchange
berry
branch
brick
umbrella
political
crack
in
goat
he
bad
dust
far
night
word
structure
mist
the
violent
stretch
keep
pot
rhythm
across
necessary
pen
other
sharp
middle
cushion
brush
cloth
reaction
chief
military
late
electric
brass
ball
married
roll
dress
under
plant
awake
camera
need
quick
knee
great
example
wing
property
seat
shoe
smoke
equal
fold
boat
sudden
wrong
start
fat
shelf
servant
past
safe
tail
cake
to
low
simple
rod
attraction
stick
trick
natural
why
rub
church
bell
you
secret
wave
humour
loud
step
disgust
canvas
idea
insect
mother
boiling
by
mark
fish
west
wine
dog
butter
where
gun
ring
bee
wool
end
basin
stem
verse
company
nail
cotton
account
who
bulb
slow
taste
note
engine
amusement
spring
face
conscious
female
go
slope
play
wood
north
drain
automatic
finger
roof
school
FALSE
loss
sound
form
new
rate
father
cord
place
pig
behaviour
material
peace
committee
board
attack
shade
see
sex
needle
but
table
hour
year
porter
salt
with
oil
flight
bed
seed
money
sweet
rule
fact
black
against
for
baby
loose
quite
support
learning
edge
tax
writing
waste
decision
damage
make
down
sand
man
sticky
wall
then
love
will
doubt
pipe
shame
little
grip
still
tree
body
pocket
left
let
morning
earth
through
pin
copper
picture
leather
representative
field
birth
egg
limit
print
thin
fiction
control
walk
discussion
payment
sleep
song
cheap
knowledge
sea
public
present
as
steam
angry
army
fire
milk
discovery
after
future
sneeze
strong
trade
question
fork
vessel
room
rough
horse
reward
slip
work
deep
nation
linen
from
rice
east
grey
while
order
blow
south
so
process
week
dry
sister
price
tendency
back
blood
jewel
I
stiff
chemical
substance
seem
group
whistle
hair
experience
bird
push
yesterday
knife
how
may
wide
general
thick
secretary
foot
certain
hammer
band
expert
hanging
bottle
attention
motion
prose
development
stage
head
cheese
effect
brother
wind
credit
language
shock
at
produce
cow
out
up
sad
bit
high
nose
complete
law
almost
music
metal
arm
frame
round
degree
sign
apple
bridge
twist
steel
self
line
noise
pencil
knot
be
small
send
snow
ice
copy
detail
bitter
chance
space
muscle
dear
put
special
top
poor
soup
industry
rest
stamp
part
destruction
a
bucket
tight
dark
bent
hospital
rail
hollow
stitch
office
competition
house
pleasure
religion
change
soft
punishment
ready
heat
page
turn
chain
train
spoon
design
tomorrow
advertisement
probable
fear
act
summer
toe
increase
yes
full
throat
much
when
woman
judge
memory
floor
different
cork
tired
liquid
kick
sugar
shut
impulse
scale
view
foolish
air
like
whip
pump
tooth
existence
name
brake
key
flower
letter
cat
tall
hearing
lead
strange
smooth
silver
cruel
nut
town
selection
test
first
base
wire
boot
tongue
enough
girl
acid
authority
spade
grain
light
broken
regret
fly
young
help
every
normal
fall
parallel
orange
leg
curve
lock
please
harbour
measure
mass
building
angle
smell
early
powder
blade
profit
street
crime
cold
paper
cart
government
record
sort
force
driving
of
lift
pain
bag
take
now
such
or
hard
meal
long
weight
flame
regular
red
common
parcel
collar
clock
meat
some
blue
fertile
cause
statement
market
scissors
thought
color
theory
value
sky
dependent
poison
comparison
green
window
among
division
station
store
wise
feather
right
art
hole
system
size
map
screw
kiss
ink
run
carriage
invention
desire
current
library
event
chalk
ticket
agreement
horn
reading
between
hook
brain
flat
protest
monkey
come
even
true
short
organization
number
power
male
operation
journey
distribution
reason
minute
story
sponge
worm
thread
apparatus
stone
frequent
friend
wet
family
sun
bath
grass
lip
iron
wash
living
machine
hat
kind
any
good
side
war
mountain
glass
quality
separate
instrument
country
together
curtain
free
approval
day
way
request
society
attempt
waiting
receipt
cup
medical
swim
all
yellow
offer
glove
person
shirt
delicate
square
feeling
teaching
narrow
drawer
paint
position
dead
meeting
solid
same
healthy
serious
last
very
owner
there
burn
private
food
touch
straight
book
son
ill
kettle
skirt
on
fruit
stocking
box
thunder
happy
guide
leaf
respect
nerve
smile
second
bright
possible
do
rat
mouth
bite
sheep
thing
farm
connection
hope
till
crush
dirty
amount
wheel
ever

View File

@@ -0,0 +1,37 @@
### Q1
For each of the following code snippets, identify the critical section(s), compute the time (T(n)) each one takes, and specify the asymptotic complexity using Big-O.
(i)
```
for(int k=0; k<n; k+=3) {
for(int p=n; p>6; p--) {
System.out.println(p%2);
}
}
O(n^2)
```
(ii)
```
for(int k=0;k<=n/8;k++) {
System.out.println(k);
}
System.out.println(“Next”);
for (int p=n; p>=1;p--) {
System.out.println(p%2);
}
O(n)
```
(iii)
```
for (int k=0; k<n-1; k++) {
for (int m=k+1; m<n; m++) {
System.out.println(k*m);
}
}
O(n^2)
```

View File

@@ -0,0 +1,23 @@
public class BubbleSort {
public static void main(String [] args) {
int [] arr = {21, 13, 8, 42, 19, 5, 34, 61};
bubbleSort(arr);
for (int i=0; i<arr.length; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void bubbleSort(int [] array) {
for (int pass=0; pass < array.length-1; pass++)
for (int i=0; i < array.length-pass-1; i++)
if (array [ i ] > array [ i+1 ])
swap(array, i, i+1);
}
public static void swap (int [ ] array, int first, int second) {
int temp = array [ first ];
array [ first ] = array [ second ];
array [ second ] = temp;
}
}

Some files were not shown because too many files have changed in this diff Show More