diff --git a/README.md b/README.md index 7b13483..211222f 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,3 @@ # JavaDataStructures -A repository for the Java programming projects I did in my Data Structures class. +A repository for the Java programming projects I did in my Data Structures class. {{Under contruction}} I need to delete all unneccesary test files/ clean up some of my code. + diff --git a/lab1/ArrayList1.class b/lab1/ArrayList1.class new file mode 100644 index 0000000..644663e Binary files /dev/null and b/lab1/ArrayList1.class differ diff --git a/lab1/ArrayList1.java b/lab1/ArrayList1.java new file mode 100644 index 0000000..65d18d8 --- /dev/null +++ b/lab1/ArrayList1.java @@ -0,0 +1,130 @@ +// file name -- ArrayList1.java +import java.io.*; +import java.util.*; + +/** + This program shows how to read in student records from an input + data fle and store them in an array list. Student records are + stored using an ArrayList object. +*/ +public class ArrayList1 +{ + private ArrayList students; + private Scanner infile; + + public static void main(String[] args) + throws IOException + { + ArrayList1 current; + + current = new ArrayList1(); + current.getStarted(); + } // method main + + private double gpa; + private double sumGPA; + private double averageGPA; + /** + Starts the program + */ + public void getStarted() + throws FileNotFoundException + { + openFile(); + readData(); + displayResults(); + System.out.println("Average GPA:" + averageGPA); + infile.close(); + } // method getStarted + + + /** + Opens the input data file for read access. + */ + public void openFile() throws FileNotFoundException + { + Scanner input; + String infile_name; + File file; + + input = new Scanner(System.in); + do + { + System.out.print("Enter the input file name: "); + infile_name = input.next(); + + // open the input data file + file = new File(infile_name); + if (file.exists()) + infile = new Scanner(new File(infile_name)); + else + System.out.println(infile_name + " does not exist"); + } while (!file.exists()); + } // method openFile + + + /** + Reads in text from file and save them in an array list. + @param infile the file which has been open successfully + */ + public void readData() + { + Student who; + String name, first_name, last_name; + int age; + + int count; + + count = 0; + sumGPA = 0; + + // instantiate an ArrayList object + students = new ArrayList(); + + // read in values from the file and assign them to the elements + while (infile.hasNext()) + { + first_name = infile.next(); + last_name = infile.next(); + name = first_name + " " + last_name; + age = infile.nextInt(); + gpa = infile.nextDouble(); + + count++; + sumGPA = sumGPA + gpa; + + + who = new Student(name, age, gpa); + students.add(who); + } + averageGPA = sumGPA / count; + + } // method readData + + + /** + Displays the student records stored in the array list. + */ + public void displayResults() + { + // display the array elements in sequence + System.out.println("The list contains " + students.size() + + " students"); + for (Student who: students) + displayStudentRecord(who); + } // method displayResults + + + /** + Displays the content of each student record. + @param who a reference to a Student object for display + */ + public void displayStudentRecord(Student who) + { + + System.out.println("Name: " + who.getName()); + System.out.println("Age: " + who.getAge()); + System.out.println("GPA: " + who.getGPA()); + + } // method displayStudentRecord +} // class ArrayList1 diff --git a/lab1/Student.class b/lab1/Student.class new file mode 100644 index 0000000..e69dca3 Binary files /dev/null and b/lab1/Student.class differ diff --git a/lab1/Student.java b/lab1/Student.java new file mode 100644 index 0000000..0da5cb7 --- /dev/null +++ b/lab1/Student.java @@ -0,0 +1,88 @@ +// file name -- Student.class + +/** + A class to represent students objects. + Many of the functions are easy to see representations of getters and setters. +*/ +public class Student +{ + private String name; + private int age; + private double gpa; + + /** + Initializes the members of a Student object. + @param name a string representing the name of the student + @param age an integer representing the age of the student + @param gpa a double value representing the gpa of the student + */ + public Student(String name, + int age, + double gpa) + { + this.name = name; + this.age = age; + this.gpa = gpa; + } // constructor + + + /** + Assigns a new name. + @param name a string representing the student's name + */ + public void setName(String name) + { + this.name = name; + } // method setName + + + /** + Assigns a new age. + @param age an integer representing the student's age + */ + public void setAge(int age) + { + this.age = age; + } // method setAge + + + /** + Assigns a new gpa. + @param age a double value representing the student's gpa + */ + public void setGPA(double gpa) + { + this.gpa = gpa; + } // method setGPA + + + /** + Returns the name of the student. + @return student's name + */ + public String getName() + { + return name; + } // method getName + + + /** + Returns the age of the student. + @return student's age + */ + public int getAge() + { + return age; + } // method getAge + + + /** + Returns the gpa of the student. + @return student's gpa + */ + public double getGPA() + { + return gpa; + } // method getGPA + +} // class Student diff --git a/lab1/student.dat b/lab1/student.dat new file mode 100644 index 0000000..2bdfb55 --- /dev/null +++ b/lab1/student.dat @@ -0,0 +1,5 @@ +James Bond 48 3.25 +Jim Smith 20 3.75 +Jean Wilson 19 3.52 +John Doe 22 2.5 +Willie Fields 25 2.95 diff --git a/lab2/FormattedInput02.class b/lab2/FormattedInput02.class new file mode 100644 index 0000000..dc1c346 Binary files /dev/null and b/lab2/FormattedInput02.class differ diff --git a/lab2/FormattedInput02.java b/lab2/FormattedInput02.java new file mode 100644 index 0000000..2cffe80 --- /dev/null +++ b/lab2/FormattedInput02.java @@ -0,0 +1,146 @@ +/** + file name -- FormattedInput02.java + This program shows how to read formatted data from a text file. + + The data file contains student records which are formatted as follows: + + Field name Columns (a.k.a. indexes) + ========================================== + Name 1 - 20 + Age 21 - 22 + gpa 23 - 27 + ssNumber 28 - 36 + ========================================== +*/ + + +import java.io.*; +import java.util.*; // for Scanner class + + +class FormattedInput02 +{ + //final keyword makes these varibales, constant values, meaning you can't change them when aprogram is running. + //private keyword makes it so that these variables can only be accesed inside of the class. + private static final int NAME_WIDTH = 20; + private static final int AGE_WIDTH = 2; + private static final int GPA_WIDTH = 5; + private static final int SSNUMBER_WIDTH = 9; + + private Scanner infile; + private ArrayList list; + + public static void main(String list[]) throws IOException + { + FormattedInput02 one; + + //makes a new instance of this class + one = new FormattedInput02(); + + one.getStarted(); + } // method main + + + /** + Default Constructor + This makes creates a new Student type array list. + */ + public FormattedInput02() + { + list = new ArrayList(); + } // constructor + + + /** + Starts the program using an object of the class + */ + public void getStarted() throws FileNotFoundException + { + openFile(); + readData(); + display(); + } // method getStarted + + + /** + Opens the input data file for read access. + */ + public void openFile() throws FileNotFoundException + { + Scanner input; + String infile_name; + File file; + + //Scanner will look for keyboard input. + input = new Scanner(System.in); + + do + { + System.out.print("Enter the input file name: "); + //gets files name. stops looking at keybaord when user presses ENTER + infile_name = input.next(); + + file = new File(infile_name); + if (file.exists()) + infile = new Scanner(file); + else + System.out.println(infile_name + " does not exist"); + } while (!file.exists()); + } // method openFile + + + /** + Reads student records from the file and separate the fields of + each record using substring method. + */ + public void readData() + { + String name, text; + int age; + double gpa; + String ssNumber; + Student who; + + while (infile.hasNextLine()) + { + text = infile.nextLine(); + + // obtain name field + name = text.substring(0, NAME_WIDTH); // extract name field + name = name.trim(); // remove leading and trailing spaces + //definetly need to use trim here, as we captured the name and all of the space behind them name and placed + //that into the name variable. + + // remove the whole name field from text. Now substring index can start at 0 again for other variables. + text = text.substring(NAME_WIDTH, text.length()); + + // extract age field from text and convert it to an int type + age = Integer.parseInt(text.substring(0, AGE_WIDTH)); + + // extract gpa field from text and convert it to a double type. We place AGE_WIDTH into the first parameter + //as gpa is after it. + gpa = Double.parseDouble(text.substring(AGE_WIDTH, AGE_WIDTH+GPA_WIDTH)); //AGE_WIDTH + GPA_WIDTH + + ssNumber = text.substring(AGE_WIDTH+GPA_WIDTH,AGE_WIDTH+GPA_WIDTH+SSNUMBER_WIDTH); + + + who = new Student(name, age, gpa, ssNumber); + //socialSecurity + + list.add(who); + } // while infile still has data + } // method readData + + + public void display() + { + for (Student who : list) + { + System.out.println("Name: " + who.getName()); + System.out.println("Age: " + who.getAge()); + System.out.println("GPA: " + who.getGPA()); + System.out.println("Social Security:" + who.getssNumber()); + } // for still student records available + } // method display + +} // class FormattedInput02 diff --git a/lab2/Student.class b/lab2/Student.class new file mode 100644 index 0000000..a048607 Binary files /dev/null and b/lab2/Student.class differ diff --git a/lab2/Student.java b/lab2/Student.java new file mode 100644 index 0000000..891de74 --- /dev/null +++ b/lab2/Student.java @@ -0,0 +1,103 @@ +// file name -- Student.class +//Your programs need to display social security number for all +//the students in addition to what being currently displayed. + + +/** + A class to represent students objects. +*/ +public class Student +{ + private String name; + private int age; + private double gpa; + private String ssNumber; + + /** + Initializes the members of a Student object. + @param name a string representing the name of the student + @param age an integer representing the age of the student + @param gpa a double value representing the gpa of the student + */ + public Student(String name, + int age, + double gpa, + String ssNumber) + { + this.name = name; + this.age = age; + this.gpa = gpa; + this.ssNumber = ssNumber; + } // constructor + + + /** + Assigns a new name. + @param name a string representing the student's name + */ + public void setName(String name) + { + this.name = name; + } // method setName + + + /** + Assigns a new age. + @param age an integer representing the student's age + */ + public void setAge(int age) + { + this.age = age; + } // method setAge + + + /** + Assigns a new gpa. + @param age a double value representing the student's gpa + */ + public void setGPA(double gpa) + { + this.gpa = gpa; + } // method setGPA + + public void setssNumber(String ssNumber) + { + this.ssNumber = ssNumber; + } + + + /** + Returns the name of the student. + @return student's name + */ + public String getName() + { + return name; + } // method getName + + + /** + Returns the age of the student. + @return student's age + */ + public int getAge() + { + return age; + } // method getAge + + + /** + Returns the gpa of the student. + @return student's gpa + */ + public double getGPA() + { + return gpa; + } // method getGPA + + public String getssNumber() + { + return ssNumber; + } + +} // class Student diff --git a/lab2/student.dat b/lab2/student.dat new file mode 100644 index 0000000..4a889ea --- /dev/null +++ b/lab2/student.dat @@ -0,0 +1,5 @@ +James Bond 48 3.25 784596322 +Jim Smith 20 3.75 123456782 +Jean Wilson 193.523276543212 +John Doe 22 2.5 015789462 +Willie Fields 252.952386418423 diff --git a/lab3/lab31.class b/lab3/lab31.class new file mode 100644 index 0000000..ac04b4d Binary files /dev/null and b/lab3/lab31.class differ diff --git a/lab3/lab31.java b/lab3/lab31.java new file mode 100644 index 0000000..4ebd94a --- /dev/null +++ b/lab3/lab31.java @@ -0,0 +1,33 @@ +/** + file name -- lab31.java +*/ + +import java.io.*; +import java.util.*; // for Scanner class +import java.util.Random; + + +class lab31 +{ + public static void main(String list[]) throws IOException + { + Random rand = new Random(); + int a; + + System.out.println("The Six Numbers Are: "); + + + //for loops + for(int i = 0; i < 6; i++) + { + //do the randomization + //need values from 1 to 54. So .nextInt(53) does 0 - 53 + //the 0 itself is set inside the function, so to bypass this we add +1 after than function + //this way if the funtion returned 0 it would be 1, if it returned 53 it would return 54. + a = rand.nextInt(53)+1; + System.out.println(a + " "); + + } + + } +} // class Triangle diff --git a/lab3/lab32.class b/lab3/lab32.class new file mode 100644 index 0000000..1f2c5bf Binary files /dev/null and b/lab3/lab32.class differ diff --git a/lab3/lab32.java b/lab3/lab32.java new file mode 100644 index 0000000..6a6548b --- /dev/null +++ b/lab3/lab32.java @@ -0,0 +1,57 @@ +/** + file name -- lab32.java + This program shows how to read data from the keyboard in Java. +*/ + + +import java.io.*; +import java.util.*; // for Scanner class +import static java.lang.Math.*; +import java.text.DecimalFormat; + + +class lab32 +{ + public static void main(String list[]) throws IOException + { + Scanner source; + double a,b,c,s,area; + //creates new decimal format object called two. This will help us format decimal numbers + DecimalFormat two = new DecimalFormat(); + //uses this method to set the decimal digits to 2 + two.setMaximumFractionDigits(2); + + source = new Scanner(System.in); + int error = 0; + + //if side doesnt meet triangle law then resend message + do { + //if side doesnt meet triangle law then resend message + System.out.print("Enter the length of the first side of the triangle: "); + a = source.nextDouble(); + + System.out.print("Enter the length of the second side of the triangle: "); + b = source.nextDouble(); + + System.out.print("Enter the length of the third side of the triangle: "); + c = source.nextDouble(); + error = 0; + + if ( a > b +c || b > a+c || c > a+c) + { + System.out.print("One side of the triangle doesnt meet the hyponenuse law, try a different number."); + error = 1; + } + + }while( error == 1); + + // calculate the semi perimeter for this triangle.total cost of the shirt's purchased + s = ( (a + b + c) / 2); + + //Uses Heron's formula + area = sqrt( s*(s-a)*(s-b)*(s-c) ); + + System.out.println("The area of the triangle with sides: " + a + ", " + b + " and " + c + " is : " + two.format(area)); + + } +} // class Triangle diff --git a/lab3/readme.md b/lab3/readme.md new file mode 100644 index 0000000..f222374 --- /dev/null +++ b/lab3/readme.md @@ -0,0 +1,6 @@ +Lab31 needs to be documented prperly. +lab31 random number generator is not properly used. It should generate number from 1 to 54. + + +The documentation for lab32 is not prperly done. + diff --git a/lab4/DoubleList$1.class b/lab4/DoubleList$1.class new file mode 100644 index 0000000..cb3e92a Binary files /dev/null and b/lab4/DoubleList$1.class differ diff --git a/lab4/DoubleList$DoubleNode.class b/lab4/DoubleList$DoubleNode.class new file mode 100644 index 0000000..192994f Binary files /dev/null and b/lab4/DoubleList$DoubleNode.class differ diff --git a/lab4/DoubleList.class b/lab4/DoubleList.class new file mode 100644 index 0000000..ce35691 Binary files /dev/null and b/lab4/DoubleList.class differ diff --git a/lab4/DoubleList.java b/lab4/DoubleList.java new file mode 100644 index 0000000..a02beee --- /dev/null +++ b/lab4/DoubleList.java @@ -0,0 +1,208 @@ +// file name -- DoubleList.java +// This file contains the definition of DoubleList class which is +// a circular doubly linked list. It also includes an inner class +// DoubleNode. Since it is an inner class, all members of this +// clas are public to the methods in the DoubleList class. + + +// ======================== packages ======================= +import java.io.*; +import java.util.*; + +public class DoubleList implements List2 +{ + private int size; + private DoubleNode head; + private DoubleNode current; + + + // ****** inner class DoubleNode **************************** + private class DoubleNode + { + private ItemType data; + private DoubleNode back_link; + private DoubleNode next_link; + }; // class DoubleNode + // ------------- end of inner class ************************ + + + public DoubleList() + // purpose -- initialize the list object + // precondition -- none + // postcondition -- size set to zero, use head to create a dummy + // node, and set both head and current point to the + // dummy node + { + makeEmpty(); + } // constructor + + + public void makeEmpty() + // purpose -- deallocate the spaces used to hold the list of nodes + // precondition -- none + // postcondition -- if list is not empty, the list nodes are freed + // from the heap. + { + head = new DoubleNode(); + head.next_link = head; + head.back_link = head; + size = 0; + current = head; + } // end makeEmpty + + + public boolean isEmpty() + // purpose -- check to see if the list is empty + // precondition -- none + // postcondition -- if list is empty, 1 is returned; otherwise 0 is + // returned. + { + return (size == 0); + } // end isEmpty + + + public int length() + // purpose -- return the length of the list. + // precondition -- none + // postcondition -- returns the number of nodes in the list. + { + return size; + } // end length + + + public void insertAfter(ItemType item) + // purpose -- insert item to the list. + // precondition -- none of the list nodes contains the same key value + // as that in item. + // postcondition -- the item is inserted after the current node of the + // list and the the size of the list is incremented + // by 1. + { + DoubleNode new_node; + + new_node = new DoubleNode(); + new_node.data = item; + + new_node.back_link = current; + new_node.next_link = current.next_link; + current.next_link.back_link = new_node; + current.next_link = new_node; + current = new_node; + + size ++; + } // end insertAfter + + + public void insertBefore(ItemType item) + // purpose -- insert item before the current node. + // precondition -- none of the list nodes contains the same key value + // as that in item. + // postcondition -- the item is inserted after the current in the list + // and the the size of the list is incremented by 1. + { + //do if condition for same key value + DoubleNode new_node; + + new_node = new DoubleNode(); + new_node.data = item; + + new_node.back_link = current.back_link; + current.back_link = new_node; + new_node.next_link = current; + new_node.back_link.next_link = new_node; + current = new_node; + + size++; + } // end insertBefore + + + public void delete(ItemType item) + // purpose -- delete a node from the list + // precondition -- the list has a node containing a key matching that + // of item. + // postcondition -- the node containing a key matching that of item is + // removed from the list and size of list is + // decremented by 1. + { + while (current.data != item) + { + current = current.next_link; + } + + if (current.data == item) + { + current.next_link.back_link = current.back_link; + current.back_link.next_link = current.next_link; + + size--; + } + } // end delete + + + public void resetList() + // purpose -- reset current so that it points to the + // beginning of the list. + // precondition -- none + // postcondition -- holds the address of the first node if list is not + // empty; otherwise, it holds NULL value. + { + //if (size != 0) {} + current = head.next_link; // goes to the link in next link of what head piints to + } // end resetList + + + public void bottom() + // purpose -- reset current so that it points to end of list. + // precondition -- none + // postcondition -- holds the address of the first node if list is not + // empty; otherwise, it holds NULL value. + { + current = head.back_link; + } // end bottom + + + public void advance() + // purpose -- advance current to next node. + // precondition -- current holds the address of a node. + // postcondition -- advance current to the next node. + { + if (current != head.back_link) + current = current.next_link; + else + current = head.next_link; + } // end advance + + + public void moveback() + // purpose -- move current to previous node. + // precondition -- current holds the address of a node. + // postcondition -- move current to the previous node. + { + if (current != head.next_link) + current = current.back_link; + else + current = head.back_link; + } // end moveback + + + public ItemType retrieve() + // purpose -- retrieve the current node data from the list. + // precondition -- current does not point to the last node of + // the list. + // postcondition -- the data of the node referenced to by the + // current is retrieved and copied to item. + { + return (current.data); + } // end retrieve + + + public void replace(ItemType data) + // purpose -- replace the data field of the current node. + // precondition -- none + // postcondition -- data field of current node is replaced with the + // data. + { + current.data = data; + } // end replace + +} // class Double List diff --git a/lab4/Driver01.class b/lab4/Driver01.class new file mode 100644 index 0000000..5502ba5 Binary files /dev/null and b/lab4/Driver01.class differ diff --git a/lab4/Driver01.java b/lab4/Driver01.java new file mode 100644 index 0000000..651de38 --- /dev/null +++ b/lab4/Driver01.java @@ -0,0 +1,73 @@ +// file name - Driver01.java + +// This program serves as the test driver for DoubleList class. +// +// Classes needed: DoubleList +// +// Interface used: List2 + + +// ============================ packages =========================== +import java.io.*; +import java.util.*; + + +public class Driver01 +{ + + public static void main(String arguments[]) throws IOException + { + DoubleList one; + + one = new DoubleList(); + + // case 1: adding a node to an empty list + System.out.println("adding a node to an empty list"); + one.insertAfter(3); + + // case 2: adding a node after current node + System.out.println("adding a node after current node"); + one.insertAfter(5); + //output should be 3 5 7 8 + // 8 7 5 3 + + // case 3: adding a node after current node + System.out.println("adding a node after current node"); + one.insertAfter(8); + one.insertBefore(7); + + // display nodes in the list + System.out.println("displaying nodes from beginning of list"); + one.resetList(); + for (int index = 0; index < one.length(); index++) + { + System.out.print(one.retrieve() + " "); + one.advance(); + } + System.out.println(); + + // display nodes in the list in reverse order + System.out.println("displaying nodes from end of list"); + one.bottom(); + for (int index = 0; index < one.length(); index++) + { + System.out.print(one.retrieve() + " "); + one.moveback(); + } + System.out.println(); + + + // display nodes with 3 deleted from the list + System.out.println("display nodes with 3 deleted from the list"); + //one.resetList(); + one.delete(5); + for (int index = 0; index < one.length(); index++) + { + System.out.print(one.retrieve() + " "); + one.advance(); + } + System.out.println(); + + } // end of main + +} // class Driver01 diff --git a/lab4/List2.class b/lab4/List2.class new file mode 100644 index 0000000..f07e229 Binary files /dev/null and b/lab4/List2.class differ diff --git a/lab4/List2.java b/lab4/List2.java new file mode 100644 index 0000000..08e35cb --- /dev/null +++ b/lab4/List2.java @@ -0,0 +1,19 @@ +// file name -- List.java +// This file contains the List interface. + +public interface List2 +{ + public void makeEmpty(); + public boolean isEmpty(); + //public boolean isLast(); + public int length(); + public ItemType retrieve(); + public void insertBefore(ItemType one); + public void insertAfter(ItemType one); + public void delete(ItemType one); + public void resetList(); + public void bottom(); + public void replace(ItemType one); + public void advance(); + public void moveback(); +} // interface List2 diff --git a/lab5/IsPostFixDemonstration.java b/lab5/IsPostFixDemonstration.java new file mode 100644 index 0000000..1f06072 --- /dev/null +++ b/lab5/IsPostFixDemonstration.java @@ -0,0 +1,102 @@ +// FILE: IsBalancedDemonstration.java +// This small demonstration program showing the isBalanced method, which uses +// a stack of characters to determine whether a string has balanced +// parentheses. + +import java.util.Stack; +import java.util.Scanner; + +public class IsPostFixExpression +{ + public static int evaluate(String expression) + { + n + } + + + + public static void main(String[ ] args) + { + Scanner stdin = new Scanner(System.in); + String expression; + + System.out.println("Please type the post fix expression containing"); // + System.out.println(" a b c d e f- + / *. I'll check whether"); // + System.out.println("the postfix expresion are balanced."); // + + do + { + System.out.print("Your string: "); + evaluate(expression) = stdin.nextLine( ); + + result = evaluate(expression); // + //if (isBalanced(expression)) //evaluate + //System.out.println("That is balanced."); + //else + // System.out.println("That is not balanced."); + } + while (query(stdin, "Another string?")); + + System.out.println("Thanks for that balancing act."); + } + + public static boolean query(Scanner input, String prompt) + { + String answer; + + System.out.print(prompt + " [Y or N]: "); + answer = input.nextLine( ).toUpperCase( ); + while (!answer.startsWith("Y") && !answer.startsWith("N")) + { + System.out.print("Invalid response. Please type Y or N: "); + answer = input.nextLine( ).toUpperCase( ); + } + + return answer.startsWith("Y"); + } + + public static boolean isBalanced(String expression) + // Postcondition: A true return value indicates that the parentheses in the + // given expression are balanced. Otherwise the return value is false. + // Note that characters other than ( ) { } and [ ] are ignored. + { + // Meaningful names for characters + final char LEFT_NORMAL = '('; + final char RIGHT_NORMAL = ')'; + final char LEFT_CURLY = '{'; + final char RIGHT_CURLY = '}'; + final char LEFT_SQUARE = '['; + final char RIGHT_SQUARE = ']'; + + Stack store = new Stack( ); // Stores parens + int i; // An index into the string + boolean failed = false; // Change to true for a mismatch + + for (i = 0; !failed && (i < expression.length( )); i++) + { + switch (expression.charAt(i)) + { + case LEFT_NORMAL: //if it sees any otehr charcters than these total constants, it will "ignore" it + case LEFT_CURLY: + case LEFT_SQUARE: + store.push(expression.charAt(i)); //pushes these to stack at index + break; + case RIGHT_NORMAL: + if (store.isEmpty( ) || (store.pop( ) != LEFT_NORMAL)) //if when u pop it it doesnt have the matchign left curly, then string not balanced. + failed = true; + break; + case RIGHT_CURLY: + if (store.isEmpty( ) || (store.pop( ) != LEFT_CURLY)) + failed = true; + break; + case RIGHT_SQUARE: + if (store.isEmpty( ) || (store.pop( ) != LEFT_SQUARE)) + failed = true; + break; + } + } + + return (store.isEmpty( ) && !failed); // return ( true if fail doesnt return true)?? + } + +} diff --git a/lab5/IsPostFixExpression.class b/lab5/IsPostFixExpression.class new file mode 100644 index 0000000..a6589c9 Binary files /dev/null and b/lab5/IsPostFixExpression.class differ diff --git a/lab5/IsPostFixExpression.java b/lab5/IsPostFixExpression.java new file mode 100644 index 0000000..bf7eff7 --- /dev/null +++ b/lab5/IsPostFixExpression.java @@ -0,0 +1,145 @@ +// FILE: IsBalancedDemonstration.java +// This small demonstration program showing the isBalanced method, which uses +// a stack of characters to determine whether a string has balanced +// parentheses. + +import java.util.Stack; +import java.util.Scanner; +import java.util.regex.Pattern; + +public class IsPostFixExpression +{ + + // This pattern will match just the first character of the next token: + public static final Pattern CHARACTER = Pattern.compile("\\S.*?"); + // These patterns match numbers at the start of the next token. The UNSIGNED versions + // must not have a plus or minus sign at the front: + //public static final Pattern DOUBLE = Pattern.compile("([+-]?((\\d+\\.?\\d*)|(\\.\\d+))([Ee][-+]?\\d+)?.*?"); + //public static final Pattern DOUBLE = Pattern.compile("([+-]?((\\d+\\.?\\d*)|(\\.\\d+))([Ee][-+]?\\d+)?.*?"); + public static final Pattern INT = Pattern.compile("[+-]?\\d+.*?"); + public static final Pattern UNSIGNED_DOUBLE = Pattern.compile("((\\d+\\.?\\d*)|(\\.\\d+))([Ee][-+]?\\d+)?.*?"); + public static final Pattern UNSIGNED_INT = Pattern.compile("\\d+.*?"); + + + + public static double evaluate(String expression) + { + Stack numbers = new Stack(); + //Stack operations = new Stack(); + + Scanner input = new Scanner(expression); + String next; + + while (input.hasNext()) + { + if (input.hasNext(UNSIGNED_INT)) + { + next = input.findInLine(UNSIGNED_INT); + numbers.push(new Double(next)); + } + + else + { + next = input.findInLine(CHARACTER); + Character operation = next.charAt(0); + + switch (operation) + { + case '+': + case '-': + case '*': + case '/': + evaluateStackTops(numbers, operation); + break; + default : + throw new IllegalArgumentException("Illegal input expression"); + } + } + } + + if (numbers.size() != 1) + { + throw new IllegalArgumentException("Illegal input expression"); + } + + System.out.println(numbers.get(0)); + return numbers.pop(); + } + + + + + + + public static void evaluateStackTops(Stack numbers, Character operation)//, Stack operations) + { + double operand1, operand2; + + if (numbers.size() < 2)//( || (operations.isEmpty())) + throw new IllegalArgumentException("Illegal expression"); + + operand2 = numbers.pop(); + operand1 = numbers.pop(); + + switch(operation)//operations.pop()) + { + case '+': + numbers.push(operand1 + operand2); + break; + case '-': + numbers.push(operand1 - operand2); + break; + case '*': + numbers.push(operand1 * operand2); + break; + case '/': + numbers.push(operand1 / operand2); + break; + + default: throw new IllegalArgumentException("Illegal operation"); + } + } + + + + + + + public static void main(String[ ] args) + { + Scanner stdin = new Scanner(System.in); + String expression; + + System.out.println("Please type the post fix expression containing"); // + System.out.println(" a b c d e f- + / *. I'll check whether"); // + System.out.println("the postfix expresion are balanced."); // + + do + { + System.out.print("Your string: "); + expression = stdin.nextLine(); //expression contains no value its just a variable atm + evaluate(expression); + } + while (query(stdin, "Thats is correct, do you want to input another string?")); + + System.out.println("Thanks for that postfix expression."); + } + + + + public static boolean query(Scanner input, String prompt) + { + String answer; + + System.out.print(prompt + " [Y or N]: "); + answer = input.nextLine( ).toUpperCase( ); + while (!answer.startsWith("Y") && !answer.startsWith("N")) + { + System.out.print("Invalid response. Please type Y or N: "); + answer = input.nextLine( ).toUpperCase( ); + } + + return answer.startsWith("Y"); + } + +} diff --git a/lab6/BinaryNode.class b/lab6/BinaryNode.class new file mode 100644 index 0000000..8a106c7 Binary files /dev/null and b/lab6/BinaryNode.class differ diff --git a/lab6/BinarySearchTree.class b/lab6/BinarySearchTree.class new file mode 100644 index 0000000..0665611 Binary files /dev/null and b/lab6/BinarySearchTree.class differ diff --git a/lab6/BinarySearchTree.java b/lab6/BinarySearchTree.java new file mode 100644 index 0000000..fcefba4 --- /dev/null +++ b/lab6/BinarySearchTree.java @@ -0,0 +1,84 @@ +// file name -- BinarySearchTree.java +// This file contains the declaration of BinarySearchTree class. + +import java.io.*; + +class BinarySearchTree> extends BinaryTree +{ + // purpose -- add an item to one of the nodes in the current binary + // search tree. + // preconditions -- item does not exist in the current binary + // serach tree. + // postconditions -- item is added to one of the nodes in the + // current binary search tree. + private BinaryNode addNode(BinaryNode start, + ItemType item) + { + if (start == null) // a new leaf node is created for insertion + { + start = new BinaryNode (); + start.info = item; + start.left = null; + start.right = null; + } + else // continue to find the place to insert a new node + { + if (item.compareTo(start.info) < 0) + start.left = addNode(start.left, item); + else + start.right = addNode(start.right, item); + } // else + + return start; + } // method addNode + + + // purpose -- search an item in the binary search tree. + // preconditions -- none + // postconditions -- if item is found in the tree, found is set + // true; otherwise, it is set to false + private void searchNode(BinaryNode start,Item item) + { + if (start == null) + { + item.setFound(false); + } // not found + else if (item.getItem().compareTo(start.info) == 0) + { + item.setItem(start.info); + item.setFound(true); + } + else + { + if (item.getItem().compareTo(start.info) < 0) + searchNode(start.left, item); + else + searchNode(start.right, item); + } + } // method searchNode + + public BinarySearchTree() {} + + + // purpose -- add an item to one of the nodes in the current binary + // search tree. + // preconditions -- item does not exist in the current binary + // serach tree. + // postconditions -- item is added to one of the nodes in the + // current binary search tree. + public void add(ItemType item) + { + root = addNode(this.root, item); + } // method add + + + // purpose -- search an item in the binary search tree. + // preconditions -- none + // postconditions -- if item is found in the tree, found is set + // true; otherwise, it is set to false + public void search(Item item) + { + searchNode(this.root, item); + } // method search + +} // class BinarySearchTree diff --git a/lab6/BinaryTree.class b/lab6/BinaryTree.class new file mode 100644 index 0000000..d527884 Binary files /dev/null and b/lab6/BinaryTree.class differ diff --git a/lab6/BinaryTree.java b/lab6/BinaryTree.java new file mode 100644 index 0000000..05ee472 --- /dev/null +++ b/lab6/BinaryTree.java @@ -0,0 +1,151 @@ +// file name -- BinaryTtree.java +// This file contains the class BinaryTree. + +import java.io.*; + +class BinaryNode +{ + ItemType info; + BinaryNode left; + BinaryNode right; +} // class BinaryNode + + +/* + * public int count() + * { + * //go to each node + } + + public int largest() + * { + * //keep moving right + * } + */ + +abstract class BinaryTree +{ + protected BinaryNode root; + int count = 0; + + // purpose -- visit and process nodes in a preorder traversal + // preconditions -- start points to the root of binary tree; one + // points to a function which will process a node in the + // tree. + // postconditions -- all nodes in the binary tree are visited in a preorder + // traversal (root, left subtree, right subtree) and each + // node is processed as it is visited. + protected void preorderVisit(BinaryNode start, + NodeProcess one) + { + if (start != null) + { + one.process(start.info); + preorderVisit(start.left, one); + preorderVisit(start.right, one); + } // if + } // method preorderVisit + + + // purpose -- visit and process nodes in a postorder traversal + // preconditions -- start points to the root of binary tree; one + // points to a function which will process a node in the + // tree. + // postconditions -- all nodes in the binary tree are visited in a + // postorder traversal (left subtree, right subtree, + // root) and each node is processed as it is visited. + protected void postorderVisit(BinaryNode start, + NodeProcess one) + { + if (start != null) + { + postorderVisit(start.left, one); + postorderVisit(start.right, one); + one.process(start.info); + } // if + } // end of binary::postorderVisit + + + // purpose -- visit and process nodes in an inorder traversal + // preconditions -- start points to the root of binary tree and + // one points to a function which will + // process a node in the tree. + // postconditions -- all nodes in the binary tree are visited in an + // inorder traversal (left subtree, root, right subtree) + // and each node is processed as it is visited. + protected void inorderVisit(BinaryNode start, + NodeProcess one) + { + if (start != null) + { + inorderVisit(start.left, one); + one.process(start.info); + inorderVisit(start.right, one); + } // if + } // end of binary::inorderVisit + + // purpose -- default constructor to set root to null + // preconditions -- none + // postconditions -- the root node is set to null + public BinaryTree() + { + root = null; + } // end of BinaryTree:BinaryTree() + + + public boolean isEmpty() + // purpose -- check to see if the tree is empty + // preconditions -- none + // postconditions -- return true if the binary tree is empty; + // otherwise, return false + { + return (root == null); + } // end of binary::isEmpty + + + public abstract void add(ItemType item); + + + public void preorderTraversal(NodeProcess one) + // purpose -- visit and process nodes in a preorder traversal + // preconditions -- one points to a function which will process + // a node in the tree. + // postconditions -- all nodes in the binary tree are visited in a preorder + // traversal (root, left subtree, right subtree) and each + // node is processed as it is visited. + { + preorderVisit(root, one); + } // end of binary::preorderTraversal + + + public void postorderTraversal(NodeProcess one) + // purpose -- visit and process nodes in a postorder traversal + // preconditions -- one points to a function which will process + // a node in the tree. + // postconditions -- all nodes in the binary tree are visited in a + // postorder traversal (left subtree, right subtree, + // root) and each node is processed as it is visited. + { + postorderVisit(root, one); + } // end of binary::postorderTraversal + + + public void inorderTraversal(NodeProcess one) + // purpose -- visit and process nodes in an inorder traversal + // preconditions -- one points to a function which will process + // a node in the tree. + // postconditions -- all nodes in the binary tree are visited in an + // inorder traversal (left subtree, root, right subtree) + // and each node is processed as it is visited. + { + inorderVisit(root, one); + } // end of binary::inorderTraversal + + + public void counter(NodeProcess one) + { + System.out.println(count); + } + + +} // class BinaryTree diff --git a/lab6/Item.class b/lab6/Item.class new file mode 100644 index 0000000..41d29a6 Binary files /dev/null and b/lab6/Item.class differ diff --git a/lab6/Item.java b/lab6/Item.java new file mode 100644 index 0000000..1da442a --- /dev/null +++ b/lab6/Item.java @@ -0,0 +1,40 @@ +// file name -- Item.java + +// This file contains the definition of Item class + +public class Item +{ + private ItemType item; + private boolean found; + + public Item(ItemType item, + boolean found) + { + this.item = item; + this.found = found; + } // constructor + + + public ItemType getItem() + { + return item; + } // method getItem + + + public boolean isFound() + { + return found; + } // method isFound + + + public void setItem(ItemType item) + { + this.item = item; + } // method setItem + + + public void setFound(boolean found) + { + this.found = found; + } // method setFound +} diff --git a/lab6/NodeProcess.class b/lab6/NodeProcess.class new file mode 100644 index 0000000..f137c3e Binary files /dev/null and b/lab6/NodeProcess.class differ diff --git a/lab6/NodeProcess.java b/lab6/NodeProcess.java new file mode 100644 index 0000000..78173d8 --- /dev/null +++ b/lab6/NodeProcess.java @@ -0,0 +1,9 @@ +// file name -- NodeProcess.java + +// This file defines the interface for processing a node in a binary tree. + + +public interface NodeProcess +{ + public void process(ItemType one); +} // interface NodeProcess diff --git a/lab6/Print.class b/lab6/Print.class new file mode 100644 index 0000000..00b083f Binary files /dev/null and b/lab6/Print.class differ diff --git a/lab6/Print.java b/lab6/Print.java new file mode 100644 index 0000000..4ab4355 --- /dev/null +++ b/lab6/Print.java @@ -0,0 +1,11 @@ +// file name -- Print.java + +// This class implements NodeProces interface + +public class Print implements NodeProcess +{ + public void process(ItemType item) + { + System.out.println(item); + } +} // class Print diff --git a/lab6/Print2.java b/lab6/Print2.java new file mode 100644 index 0000000..c4e157f --- /dev/null +++ b/lab6/Print2.java @@ -0,0 +1,14 @@ +// file name -- Print2.java + +// This class implements Item interface + +public class Print2 implements Item +{ + public void process(Item item) + { + System.out.println(item); + } +} // class Print + + +WRONG diff --git a/lab6/ShowBinarySearchTree01.class b/lab6/ShowBinarySearchTree01.class new file mode 100644 index 0000000..c8a71b8 Binary files /dev/null and b/lab6/ShowBinarySearchTree01.class differ diff --git a/lab6/ShowBinarySearchTree01.java b/lab6/ShowBinarySearchTree01.java new file mode 100644 index 0000000..1c2117f --- /dev/null +++ b/lab6/ShowBinarySearchTree01.java @@ -0,0 +1,32 @@ +// file name -- ShowBinarySearchTree01.java + +// This program demonstrates how to use the BinarySearchTree class. + +// ============================ packages ============================= +import java.io.*; + +public class ShowBinarySearchTree01 +{ + + public static void main(String arguments[]) throws IOException + { + BinarySearchTree one; + + one = new BinarySearchTree(); + + one.add(9); + one.add(15); + one.add(51); + one.add(5); + one.add(1); + one.add(3); + one.add(23); + one.add(83); + one.add(21); + one.add(58); + one.add(71); + one.add(91); + one.inorderTraversal(new Print()); + + } // method main +} // class ShowBinarySearchTree01 diff --git a/lab6/ShowBinarySearchTree02.class b/lab6/ShowBinarySearchTree02.class new file mode 100644 index 0000000..817ed14 Binary files /dev/null and b/lab6/ShowBinarySearchTree02.class differ diff --git a/lab6/ShowBinarySearchTree02.java b/lab6/ShowBinarySearchTree02.java new file mode 100644 index 0000000..e717f2d --- /dev/null +++ b/lab6/ShowBinarySearchTree02.java @@ -0,0 +1,90 @@ +// file name -- ShowBinarySearchTree02.java + +// This program demonstrates how to use the BinarySearchTree class. + +// =========================== packages ============================= +import java.io.*; +import java.util.*; + + +public class ShowBinarySearchTree02 +{ + private BinarySearchTree tree; + private Scanner keyboard; + private final int MAX = 10; + + public static void main(String arguments[]) throws IOException + { + ShowBinarySearchTree02 one; + + one = new ShowBinarySearchTree02(); + one.getStarted(); + } // method main + + + // default constructor + public ShowBinarySearchTree02() + { + tree = new BinarySearchTree (); + keyboard = new Scanner(System.in); + } // default constructor + + + // create the binary search tree first and display the tree + // using three different traversal methods + public void getStarted() + { + createBinarySearchTree(); + displayInorder(); + displayPreorder(); + displayPostorder(); + } // method getStarted + + + void createBinarySearchTree() + // This method uses random numbers to create a binary search tree. + // The values are generated between -MAX+1 and MAX-1 inclusive. + { + Random number = new Random(); + int value; + int k; + + System.out.println("Numbers to be inserted to the binary search tree are: "); + for (k = 1; k <= MAX; k ++) + { + value = number.nextInt(10 * MAX); + if (k % 2 == 0) + value = -value; + System.out.print(value + " "); + tree.add(value); + } // for k + System.out.println(); + } // end of createBinarySearchTree + + + void displayInorder() + // This function displays the nodes in a binary search tree in an + // inorder traveral. + { + System.out.println("values printed using an inorder traversal: "); + tree.inorderTraversal(new Print()); + } // end of displayInorder + + + void displayPreorder() + // This function displays the nodes in a binary search tree in a + // preorder traveral. + { + System.out.println("values printed using an preorder traversal: "); + tree.preorderTraversal(new Print()); + } // end of displayPreorder + + + void displayPostorder() + // This function displays the nodes in a binary search tree in a + // postorder traveral. + { + System.out.println("values printed using an postorder traversal: "); + tree.postorderTraversal(new Print()); + } // end of displayPostorder +} // class ShowBinarySearchTree02 diff --git a/lab6/ShowBinarySearchTree03.class b/lab6/ShowBinarySearchTree03.class new file mode 100644 index 0000000..a353892 Binary files /dev/null and b/lab6/ShowBinarySearchTree03.class differ diff --git a/lab6/ShowBinarySearchTree03.java b/lab6/ShowBinarySearchTree03.java new file mode 100644 index 0000000..8d9bd76 --- /dev/null +++ b/lab6/ShowBinarySearchTree03.java @@ -0,0 +1,39 @@ +// file name -- ShowBinarySearchTree03.java +// This program demonstrates how to use the BinarySearchTree class. + +// =========================== packages ============================== +import java.io.*; + + +public class ShowBinarySearchTree03 +{ + public static void main(String argumentts[]) throws IOException + { + BinarySearchTree one; + Item item; + + one = new BinarySearchTree(); + one.add("Chris"); + one.add("James"); + one.add("Jackson"); + one.add("April"); + one.add("Wells"); + one.add("Alice"); + one.add("Rice"); + one.add("Melanie"); + one.add("Gail"); + one.add("John"); + one.add("Simpson"); + one.add("Cream"); + one.inorderTraversal(new Print()); + + // perform search + item = new Item("Creame", true); + one.search(item); + System.out.println(item.getItem() + " " + item.isFound()); + + item = new Item("Melanie", false); + one.search(item); + System.out.println(item.getItem() + " " + item.isFound()); + } // end of main +} // class ShowBinaryTree03 diff --git a/lab6/ShowBinarySearchTreeLab.class b/lab6/ShowBinarySearchTreeLab.class new file mode 100644 index 0000000..c22271f Binary files /dev/null and b/lab6/ShowBinarySearchTreeLab.class differ diff --git a/lab6/ShowBinarySearchTreeLab.java b/lab6/ShowBinarySearchTreeLab.java new file mode 100644 index 0000000..e49324b --- /dev/null +++ b/lab6/ShowBinarySearchTreeLab.java @@ -0,0 +1,51 @@ +// file name -- ShowBinarySearchTree01.java + +// This program demonstrates how to use the BinarySearchTree class. + +// ============================ packages ============================= +import java.io.*; +import java.util.Scanner; + + +public class ShowBinarySearchTreeLab +{ + + public static void main(String arguments[]) throws IOException + { + BinarySearchTree one; + one = new BinarySearchTree(); + + Scanner infile; + int value; + + infile = new Scanner(new FileReader("lab6.dat")); //reads numbers from file lab6.dat + while (infile.hasNextInt()) //this is a Loop for getting numbers + { + value = infile.nextInt(); + one.add(value); + } +/* + one.add(9); + one.add(15); + one.add(51); + one.add(5); + one.add(1); + one.add(3); + one.add(23); + one.add(83); + one.add(21); + one.add(58); + one.add(71); + one.add(91); +*/ + one.inorderTraversal(new Print()); + + //one.count + //one.largest + + } // method main +} // class ShowBinarySearchTree01 + + + + diff --git a/lab6/lab6.dat b/lab6/lab6.dat new file mode 100644 index 0000000..be182fa --- /dev/null +++ b/lab6/lab6.dat @@ -0,0 +1,15 @@ +100 +50 +150 +40 +60 +30 +42 +55 +65 +140 +160 +120 +145 +155 +170 diff --git a/lab6/lab6b.class b/lab6/lab6b.class new file mode 100644 index 0000000..b81cfa9 Binary files /dev/null and b/lab6/lab6b.class differ diff --git a/lab6/lab6b.java b/lab6/lab6b.java new file mode 100644 index 0000000..0c7297f --- /dev/null +++ b/lab6/lab6b.java @@ -0,0 +1,138 @@ +// file name -- ShowBinarySearchTree02.java + +// This program demonstrates how to use the BinarySearchTree class. + +// =========================== packages ============================= +import java.io.*; +import java.util.*; + + +public class lab6b +{ + private BinarySearchTree tree; + private Scanner keyboard; + private final int MAX = 10; + + public static void main(String arguments[]) throws IOException + { + lab6b one; + + one= new lab6b(); + one.getStarted(); + } // method main + + + + public lab6b() + // default constructor + { + tree= new BinarySearchTree (); + keyboard = new Scanner(System.in); + } // default constructor + + + public void getStarted() throws FileNotFoundException + // create the binary search tree first and display the tree + // using three different traversal methods + { + createBinarySearchTree(); + displayInorder(); + greatestNode(tree.root); + counter(tree.root); + System.out.println("The Number of nodes is: " + counter(tree.root)); //binary tree name + System.out.println("The Largest number is: " + greatestNode(tree.root)); + + } // method getStarted + + + public Scanner openFile() throws FileNotFoundException + { + Scanner input, infile = null; + String infile_name; + File outfile; + + input = new Scanner(System.in); + + do + { + System.out.println("Please enter the input file name: "); + + infile_name = input.next(); + + outfile = new File(infile_name); + + + try + { + infile = new Scanner(outfile); + } + + catch (FileNotFoundException ex) + { + System.out.println(infile_name + " does not exist"); + } + + }while(!outfile.exists()); + + return infile; + } + + + void createBinarySearchTree() throws FileNotFoundException + { + + Scanner infile = openFile(); + + while(infile.hasNext()) + { + tree.add(infile.nextInt()); + } + } // end of createBinarySearchTree + + + void displayInorder() + // This function displays the nodes in a binary search tree in an + // inorder traveral. + { + tree.inorderTraversal(new Print()); + } // end of displayInorder + + + public int greatestNode(BinaryNode node) + // This function will find the largest value in the tree. + { + int highest; + + if ( node == null) + return 0; // if tree is empty + + else + highest = greatestNode(node.right); //keeps finding nodes + + if(node.info > highest) //adds new highest if the current node is greater + highest = node.info; + + return highest; + } + //end of finding the highest number + + + + public int counter(BinaryNode node) + // This function count will count the number of nodes in the tree. + { + int count = 1; + + if (node == null) + return 0; + + else + { + count += counter(node.left); + count += counter(node.right); + + return count; + } + } +} + // class lab6b