Notes on CB Video

The Public Interface of a Class

public class Person {
    public Person(String name, int age, String location) { // Constructor header w/ parameters
        // pass
    }

    public String getName(String name, int age, String location) { // Accessor Method, will return value
        // pass
    }

    public int getAge() { // Accessor Method, will return value
        // pass
    }

    public String getLocation() { // Accessor Method, will return value
        // pass
    }

    public void changeLocation(String newLocation) { // Mutator Method, change the state of an object
        // pass
    }

    public void haveABirthday() { // Mutator Method, change the state of an object
        // pass
    }
}

public static void main(String[] args) {
    // Person = class
    // teacher = Object name
    // "Mr. Mort", 21, "San Diego" = Actual parameters
    Person teacher = new Person("Mr. Mort", 21, "San Diego");
    Person student = new Person("Yash", 18, "San Diego");

    String location = teacher.getLocation();
    System.out.println(location); // prints San Diego

    student.haveABirthday();

    System.out.println(student.getName()); // prints Yash
    System.out.println(student.getAge()); // prints 18

    teacher.changeLocation("Washington");
    System.out.println(teacher.getName()); // prints Mr. Mort
    System.out.println(teacher.getLocation()); // prints Washington
}

The Math Class

  • Provides static methods that can be utilized through class.method() convention
Method What It Does
static int abs(int x) Returns absolute value of int x
static double abs(double x) Returns the absolute value of double x
static double pow(double base, double exponent) Returns first parameter to the power of the second parameter
static double sqrt(double x) Returns the positive square root of double x
static double random() Returns a double value greater than or equal to 0.0 and less than 1.0
System.out.println("abs(int x):");
System.out.println(Math.abs(-45));

System.out.println("\nabs(double x):");
System.out.println(Math.abs(-12.5));

System.out.println("\npow(double x, double y):");
System.out.println(Math.pow(3, 2));

System.out.println("\nsqrt(double x):");
System.out.println(Math.sqrt(16.0));

System.out.println("\nrandom():");
System.out.println(Math.random() * 100);
abs(int x):
45

abs(double x):
12.5

pow(x, y):
9.0

sqrt(16):
4.0

random():
70.86644341962915

Using String Class Objects

String word = "theater";

Method What Does It Do
String(String str) Constructs new String object that represents the same sequence of characters
int length() Returns the number of characters in a String object
String substring(int from, int to) Returns the substring beginning at index from and ending at index to - 1
String substring(int from) Returns substring(from,length())
int indexOf(String str) Returns the index of the first occurrence of str; returns -1 if not found
boolean equals(String other) Returns true if this is equal to other; returns false otherwise
int compareTo(String other) Returns a value < 0 if this is less than other; returns 0 if this is equal to other; returns a value > 0 if this is greater than other
String word = "THEATER";
System.out.println("\033[0;1m" + word + "\033[0;0m");

System.out.println("\nlength():");
System.out.println(word.length());

System.out.println("\nsubstring(int x, int y):");
System.out.println(word.substring(1,5));

System.out.println("\nsubstring(int x):");
System.out.println(word.substring(2));

System.out.println("\nindexOf(String str):");
System.out.println(word.indexOf("ate"));

System.out.println("\nequals(String other):");
System.out.println(word.equals("THEATER"));

System.out.println("\nequals(String other):");
System.out.println(word.equals("MOVIE"));

System.out.println("\ncompareTo(String other):");
System.out.println(word.compareTo("MOVIE THEATER"));
THEATER

length():
7

substring(int x, int y):
HEAT

substring(int x):
EATER

indexOf(String str):
-1

equals(String other):
true

equals(String other):
false

compareTo(String other):
7

2021 FRQ 2 - combinedTable - Canonical Solution

public class combinedTable { // Class header
    
    private SingleTable table1; // Declare private instance variables
    private SingleTable table2; // Declare private instance variables


    public CombinedTable(SingleTable t1, SingleTable t2 /* Constructor header w/ parameters */) {
        table1 = t1; // Initialize instance variable
        table2 = t2; // Initialize instance variable
    }

    
    public boolean canSeat(int n) { // Method header w/ parameter
        if (table1.getNumSeats() + table2.getNumSeats()-2 >= n) {
            return true;
        } else {
            return false;
        }
    }

    
    public double getDesirability() { //Method header w/o parameter
        if (table1.getHeight() == table2.getHeight()) {
            return (table1.getViewQuality() + table2.getViewQuality()) / 2;
        } else {
            return (table1.getViewQuality() + table2.getViewQuality()) / 2 - 10;
        }
    }
}

Queues

class LLQS {
    
    // Queue testing, inits queue 
    public void queueTesting() {
        Queue<Integer> q = new LinkedList<Integer>();

        System.out.println("Adding to Queue");

        for (int i = 1; i < 10; i = i + 1) {
            q.add(i);
            printQueue(q);
            System.out.println();
        }

        queueToStack(q);

    }

    // Prints queue regardless of type
    public void printQueue(Queue<?> q) {
        for (Object i : q) {
            System.out.print(i);
        }
    }

    public void queueToStack(Queue<?> q) {
        // create new stack with type T
        Stack<Object> tempStack = new Stack<>();

        System.out.println("");
        System.out.println("Queue to Stack");

        while (!q.isEmpty() ) {
            // push queue element to stack and remove from queue
            tempStack.push(q.remove());
            printStack(tempStack);
            System.out.println();
        }
    }

    // Print stack
    public void printStack(Stack<?> s) {
        for (Object i : s) {
            System.out.print(i);
        }
    }


    public static void main(String[] args) {
        LLQS a = new LLQS();
        a.queueTesting();
    }
}

LLQS.main();
|           Queue<Integer> q = new LinkedList<Integer>();
no suitable constructor found for LinkedList(no arguments)
    constructor LinkedList.LinkedList(java.lang.Integer,LinkedList<java.lang.Integer>) is not applicable
      (actual and formal argument lists differ in length)
    constructor LinkedList.LinkedList(LinkedList<java.lang.Integer>) is not applicable
      (actual and formal argument lists differ in length)

|           while (!q.isEmpty() ) {
cannot find symbol
  symbol:   method isEmpty()

|               tempStack.push(q.remove());
cannot find symbol
  symbol:   method remove()

Add/Delete items from queue

import java.util.Iterator;

/*
 * Queue Iterator
 * 1. "has a" current reference in Queue
 * 2. supports iterable required methods for next that returns a generic T Object
 */
/*
 *  Implementation of a Double Linked List; forward and backward links point to adjacent Nodes.
 */

public class LinkedList<T> {
    private T data;
    private LinkedList<T> prevNode, nextNode;

    /*
     *  Constructs a new element
     * @param data, data of object
     * @param node, previous node
     */
    public LinkedList(T data, LinkedList<T> node) {
        this.setData(data);
        this.setPrevNode(node);
        this.setNextNode(null);
    }

    /*
     * Clone an object,
     * @param node object to clone
     */
    public LinkedList(LinkedList<T> node) {
        this.setData(node.data);
        this.setPrevNode(node.prevNode);
        this.setNextNode(node.nextNode);
    }

    /*
     * Setter for T data in DoubleLinkedNode object
     * @param  data, update data of object
     */
    public void setData(T data) {
        this.data = data;
    }

    /*
     * Returns T data for this element
     * @return  data associated with object
     */
    public T getData() {
        return this.data;
    }

    /*
     * Setter for prevNode in DoubleLinkedNode object
     * @param node, prevNode to current Object
     */
    public void setPrevNode(LinkedList<T> node) {
        this.prevNode = node;
    }

    /*
     * Setter for nextNode in DoubleLinkedNode object
     * @param node, nextNode to current Object
     */
    public void setNextNode(LinkedList<T> node) {
        this.nextNode = node;
    }


    /*
     * Returns reference to previous object in list
     * @return  the previous object in the list
     */
    public LinkedList<T> getPrevious() {
        return this.prevNode;
    }

    /*
     * Returns reference to next object in list
     * @return the next object in the list
     */
    public LinkedList<T> getNext() {
        return this.nextNode;
    }

}

class QueueIterator<T> implements Iterator<T> {
    LinkedList<T> current;  // current element in iteration

    // QueueIterator is pointed to the head of the list for iteration
    public QueueIterator(LinkedList<T> head) {
        current = head;
    }

    // hasNext informs if next element exists
    public boolean hasNext() {
        return current != null;
    }

    // next returns data object and advances to next position in queue
    public T next() {
        T data = current.getData();
        current = current.getNext();
        return data;
    }
}

/*
 * Queue: custom implementation
 * @author John Mortensen
 * 1. Uses custom LinkedList of Generic type T
 * 2. Implements Iterable
 * 3. "has a" LinkedList for head and tail
 */
public class Queue<T> implements Iterable<T> {
    LinkedList<T> head = null, tail = null;

    /*
     * Add a new object at the end of the Queue,
     * @param data, is the data to be inserted in the Queue.
     */
    public void add(T data) {
        // add new object to end of Queue
        LinkedList<T> tail = new LinkedList<>(data, null);

        if (this.head == null)  // initial condition
            this.head = this.tail = tail;
        else {  // nodes in queue
            this.tail.setNextNode(tail); // current tail points to new tail
            this.tail = tail;  // update tail
        }
    }

    /*
     * Returns the data of head.
     * @return  data, the dequeued data
     */
    public T delete() {
        T data = this.peek();
        if (this.tail != null) { // initial condition
            this.head = this.head.getNext(); // current tail points to new tail
            if (this.head != null) {
                this.head.setPrevNode(tail);
            }
        }
        return data;
    }

    /*
     * Returns the data of head.
     * @return this.head.getData(), the head data in Queue.
     */
    public T peek() {
        return this.head.getData();
    }

    /*
     * Returns the head object.
     * @return this.head, the head object in Queue.
     */
    public LinkedList<T> getHead() {
        return this.head;
    }

    /*
     * Returns the tail object.
     * @return this.tail, the last object in Queue
     */
    public LinkedList<T> getTail() {
        return this.tail;
    }

    /*
     * Returns the iterator object.
     * @return this, instance of object
     */
    public Iterator<T> iterator() {
        return new QueueIterator<>(this.head);
    }
}

public class QueueManager<T> {
    // queue data
    private final String name; // name of queue
    private int count = 0; // number of objects in queue
    public final Queue<T> queue = new Queue<>(); // queue object

    /*
     * Queue constructor
     * Title with empty queue
     */
    public QueueManager(String name) {
        this.name = name;
    }

    /*
     * Queue constructor
     * Title with series of Arrays of Objects
     */
    public QueueManager(String name, T[]... seriesOfObjects) {
        this.name = name;
        this.addList(seriesOfObjects);
    }

    /*
     * Add a list of objects to queue
     */
    public void addList(T[]... seriesOfObjects) {  //accepts multiple generic T lists
        for (T[] objects: seriesOfObjects)
            for (T data : objects) {
                this.queue.add(data);
                this.count++;
                printQueue();
            }
    }

    // add single object to queue
    public void add(T data) {
        this.queue.add(data);
        this.count++;
        printQueue();
    }

    // delete objects from queue
    public void deleteList(int count) {
        for (int i = 0; i < count; i = i + 5) {
            this.queue.delete();
            this.count--;
            printQueue();
        }
    }

    /*
     * Print any array objects from queue
     */
    public void printQueue() {
        System.out.println(this.name + " count: " + count);
        System.out.print(this.name + " data: ");
        for (T data : queue)
            System.out.print(data + " ");
        System.out.println();
    }
}

class QueueTester {
    public static void main(String[] args) {
        // create queue manager
        QueueManager<Integer> qm = new QueueManager<>("Queue");

        // add objects to queue
        qm.addList(new Integer[]{5, 10, 15, 20, 25});

        // delete objects from queue
        qm.deleteList(5);
    }
}

QueueTester.main(null);
Queue count: 1
Queue data: 5 
Queue count: 2
Queue data: 5 10 
Queue count: 3
Queue data: 5 10 15 
Queue count: 4
Queue data: 5 10 15 20 
Queue count: 5
Queue data: 5 10 15 20 25 
Queue count: 4
Queue data: 10 15 20 25