import java.util.*;
import java.util.ArrayList;

public class binaryConverter {
    public static ArrayList binaryAddition(int num1, int num2) {
        int added;
        String z;
        ArrayList<Integer> bArray = new ArrayList<>();
        StringBuilder sb = new StringBuilder();

        for (int j = num1 + num2; j > 0; j = j/2) {
            added = j;
            if (added % 2 == 0) {
                bArray.add(0,0);
            }
            else {
                bArray.add(0,1);
            }
        }
        
        System.out.println(bArray);

        for (int x : bArray) {
            System.out.print(x + " ");
        }
        return bArray;
    } 

    public static void main(String[] arg) {
        System.out.println("Binary of 120 + 2");
        binaryConverter.binaryAddition(120, 2);
        System.out.println();
        System.out.println();
        System.out.println("Binary of 20 + 40");
        binaryConverter.binaryAddition(20,40);
        System.out.println();
        System.out.println();
        System.out.println("Binary of 25 + 47");
        binaryConverter.binaryAddition(25,47);
        System.out.println();
        System.out.println();
        System.out.println("Binary of 2 + 2");
        binaryConverter.binaryAddition(2,2);
        
    }
}
binaryConverter.main(null);
Binary of 120 + 2
[1, 1, 1, 1, 0, 1, 0]
1 1 1 1 0 1 0 

Binary of 20 + 40
[1, 1, 1, 1, 0, 0]
1 1 1 1 0 0 

Binary of 25 + 47
[1, 0, 0, 1, 0, 0, 0]
1 0 0 1 0 0 0 

Binary of 2 + 2
[1, 0, 0]
1 0 0 

Notes

  • by value vs by reference
  • inside object is a value
  • there is a structure around the value and the value is referenced to
  • vs the value specifically in primitive
  • two data types primitive and reference
  • different ways that variables exist
  • reference - inside of the structure there is pointers to memory locations; addresses that are pointing to variables; stored in the heap and reference points to the memory
  • primitive - local variable that is kept for you
  • wrapper class converts primitives to objects
  • ex: int to Integer however Integer does not behave like a class
  • object is a type of reference
  • variables are called a stack
  • variables either point to values directly in the stack (primitives) or to memory locations called heap (reference)
  • String is a class because it is a collection of characters
  • class has data and methods and can mix data types
  • array can only have 1 data type
  • primitive is stored locally, it is not the same variable each time
  • passing reference variable passes the reference so they will change method to method
  • passing primitive variables will not change between methods; you would only be changing local variables in methods
public class closestToVar {
    int n = 
    
    public static int closestTo(int n, Arraylist x) {
        
    }
}

closestToVar.main(null);
|       public static int closestTo(int n, Arraylist x) {
illegal start of expression
public class IntByValue {
    
    public static void changeInt(int n) {
        System.out.println("In changeInt method");
        System.out.println("\tBefore n += 10: n = " + n); // prints 5
        n = n += 10;
        System.out.println("\tAfter n += 10: n = " + n); // prints 10
    }

    public static void main(String[] args) {
        int n = 5;
        System.out.println("Main method before changeInt(n): n = " + n); // prints 5
        changeInt(n);
        System.out.println("Main method after changeInt(n): n = " + n); // still prints 5
    }
}
IntByValue.main(null);
Main method before changeInt(n): n = 5
In changeInt method
	Before n += 10: n = 5
	After n += 10: n = 15
Main method after changeInt(n): n = 5
public class IntegerByValueOrReference {
    
    public static void changeInteger(Integer n) {
        System.out.println("In changeInteger method");
        System.out.println("\tBefore change: n = " + 
                            n + // prints 5
                            " hash code = " + 
                            n.hashCode()); 

        n += 10;  // behind the scenes, this is:  n = new Integer(n+10)
        
        System.out.println("\tAfter change: n = " + 
                            n + // prints 15
                            " hash code = " + 
                            n.hashCode()); 
    }

    public static void main(String[] args) {
        Integer n = 5;
        System.out.println("Main method before changeInteger(n): n = " + 
                            n + // prints 5
                            " hash code = " + 
                            n.hashCode()); 

        changeInteger(n);
        
        System.out.println("Main method after changeInteger(n): n = " + 
                            n +  // now prints 15
                            " hash code = " + 
                            n.hashCode());     
    }
}
IntegerByValueOrReference.main(null);
Main method before changeInteger(n): n = 5 hash code = 5
In changeInteger method
	Before change: n = 5 hash code = 5
	After change: n = 15 hash code = 15
Main method after changeInteger(n): n = 5 hash code = 5
import java.util.concurrent.atomic.AtomicInteger;

public class PassByReference {
    
    public static void changeAtomicInteger(AtomicInteger n) {
        System.out.println("In changeAtomicInteger method");
        System.out.println("\tBefore change: n = " + 
                            n + // prints 5
                            " hash code = " + 
                            n.hashCode()); 
        n.set(n.get() + 10);  // at this point, we are clearly working with reference data type
        System.out.println("\tAfter change: n = " + 
                            n + // prints 15
                            " hash code = " + 
                            n.hashCode()); 
}

    public static void main(String[] args) {
        AtomicInteger n = new AtomicInteger(5); // unlike conventional wrapper class, this requires new
        System.out.println("Main method before changeAtomicInteger(n): n = " + 
                            n + // prints 5
                            " hash code = " + 
                            n.hashCode()); 
        changeAtomicInteger(n);
        System.out.println("Main method after changeAtomicInteger(n): n = " + 
                            n +  // now prints 15
                            " hash code = " + 
                            n.hashCode()); 
    }
}
PassByReference.main(null);
Main method before changeAtomicInteger(n): n = 5 hash code = 2065340154
In changeAtomicInteger method
	Before change: n = 5 hash code = 2065340154
	After change: n = 15 hash code = 2065340154
Main method after changeAtomicInteger(n): n = 15 hash code = 2065340154
public class IntByReference {
    private int value;

    public IntByReference(Integer value) {
        this.value = value;
    }

    public String toString() {
        return (String.format("%d", this.value));
    }

    public void swapToLowHighOrder(IntByReference i) {
        if (this.value > i.value) {
            int tmp = this.value;
            this.value = i.value;
            i.value = tmp;
        }
    }

    public static void swapper(int n0, int n1) {
        IntByReference a = new IntByReference(n0);
        IntByReference b = new IntByReference(n1);
        System.out.println("Before: " + a + " " + b);
        a.swapToLowHighOrder(b);  // conditionally build swap method to change values of a, b
        System.out.println("After: " + a + " " + b);
        System.out.println();
    }

    public static void main(String[] ags) {
        IntByReference.swapper(21, 16);
        IntByReference.swapper(16, 21);
        IntByReference.swapper(16, -1);
    }

}
IntByReference.main(null);
Before: 21 16
After: 16 21

Before: 16 21
After: 16 21

Before: 16 -1
After: -1 16

Small Code Excercises

int vs Integer

public class primitiveExample {
    public static void greatestIntInArray(int[] arr) {
        int max = 0;
        for (int n : arr) {
            if (n > max) {
                max = n;
            }
        }
        System.out.println("The maximum number in the array is " + max);
    }

    public static void main(String[] arg) {
        int[] tester = {43,54,23,65,78,85,88,92,10};
        primitiveExample.greatestIntInArray(tester);
    }
}
primitiveExample.main(null);
The maximum number in the array is 92
public class wrapperExample {
    public static void greatestIntegerInArray(Integer[] arr) {
        Integer max = 0;
        for (Integer n : arr) {
            if (n > max) {
                max = n;
            }
        }
        System.out.println("The maximum number in the array is " + max);
    }

    public static void main(String[] arg) {
        Integer[] tester = {43,54,23,65,78,85,88,92,10};
        wrapperExample.greatestIntegerInArray(tester);
    }
}
wrapperExample.main(null);
The maximum number in the array is 92

double vs Double

import java.util.*;
public class primitiveExample {
    public static void smallestDoubleArray(double[] arr) {
        double min = 100000;
        for (double n : arr) {
            if (n < min) {
                min = n;
            }
        }
        System.out.println("The minimum number in the array is " + min);
    }

    public static void main(String[] arg) {
        double[] tester = new double[10];
        for (int j = 0; j < 10; j++) {
            double x = Math.random();
            tester[j] = x;
        }
        System.out.println("Original array " + Arrays.toString(tester));
        primitiveExample.smallestDoubleArray(tester);
    }
}
primitiveExample.main(null);
Original array [0.22729475334448135, 0.48211900754345005, 0.07435759459797553, 0.9680458867726401, 0.2737927656314638, 0.3997104014181716, 0.5645032050550602, 0.9582097378661634, 0.4815384177959833, 0.45514285711532]
The minimum number in the array is 0.07435759459797553
import java.util.*;
public class wrapperExample {
    public static void smallestDoubleArray(Double[] arr) {
        Double min = 100000.0;
        for (Double n : arr) {
            if (n < min) {
                min = n;
            }
        }
        System.out.println("The minimum number in the array is " + min);
    }

    public static void main(String[] arg) {
        Double[] tester = new Double[10];
        for (Integer j = 0; j < 10; j++) {
            Double x = Math.random();
            tester[j] = x;
        }
        System.out.println("Original array " + Arrays.toString(tester));
        wrapperExample.smallestDoubleArray(tester);
    }
}
wrapperExample.main(null);
Original array [0.20862486201640618, 0.677846505993182, 0.6472488902012384, 0.2995302577315666, 0.7898046557093028, 0.8269508850611832, 0.8219311744911059, 0.61369659155693, 0.5313837155000881, 0.5491872913479079]
The minimum number in the array is 0.20862486201640618

boolean vs Boolean

import java.util.*;
public class primitiveExample {
    public static boolean isNumEven(int x) {  
        if (x%2 == 0) {
            System.out.println("true");
            return true;
        }  
        else {
            System.out.println("false");
            return false;
        }
    }
    public static void main(String[] arg) {
        System.out.println("Is 5 even?");
        primitiveExample.isNumEven(5);
        System.out.println("Is 148 even?");
        primitiveExample.isNumEven(148);
        System.out.println("Is 3 even?");
        primitiveExample.isNumEven(3);

    }
}
primitiveExample.main(null);
Is 5 even?
false
Is 148 even?
true
Is 3 even?
false
import java.util.*;
public class wrapperExample {
    public static Boolean isNumEven(int x) {  
        if (x%2 == 0) {
            System.out.println("true");
            return true;
        }  
        else {
            System.out.println("false");
            return false;
        }
    }
    public static void main(String[] arg) {
        System.out.println("Is 5 even?");
        wrapperExample.isNumEven(5);
        System.out.println("Is 148 even?");
        wrapperExample.isNumEven(148);
        System.out.println("Is 3 even?");
        wrapperExample.isNumEven(3);

    }
}
wrapperExample.main(null);
Is 5 even?
false
Is 148 even?
true
Is 3 even?
false

char vs Character

public class primitiveExample {
 
    public static void main(String[] args) {
         
        char c1 = 'A';
        System.out.println("The value of c1 is: " + c1);
         
        c1++;
        System.out.println("After incrementing: " + c1);

        c1++;
        System.out.println("After incrementing: " + c1);
         
        c1--;
        System.out.println("After decrementing: " + c1);
         
    }
 
}
primitiveExample.main(null);
The value of c1 is: A
After incrementing: B
After incrementing: C
After decrementing: B
public class wrapperExample {
 
    public static void main(String[] args) {
         
        Character c1 = 'A';
        System.out.println("The value of c1 is: " + c1);
         
        c1++;
        System.out.println("After incrementing: " + c1);

        c1++;
        System.out.println("After incrementing: " + c1);
         
        c1--;
        System.out.println("After decrementing: " + c1);
         
    }
 
}wrapperExample.main(null);
The value of c1 is: A
After incrementing: B
After incrementing: C
After decrementing: B

More Notes

Methods and Control Structures:

A method is a set of code which is referred to by name and can be called at any point in a program. A method has a declaration and a body. The declaration includes the access level, return type, name, and parameters. The body contains the statements implemented by the method. There are two types of methods: built-in and user-defined.

Control structures are a way to specify flow of control in programs. It is like a block of programming that analyses variables and and chooses a direction in ehich to go based on given parameters. There are two main control structures: loops and conditionals.

Diverse Arrays

This class does contain methods and control structures. There are 3 main methods that are meant for 2D arrays. There are also control strcutures because there are for loops and if statements. This class includes 2D arrays. It includes integers, booleans, and arrays. It is all primitive data types.

DoNothingByValue

The key knowledge is that this class makes changes to an array of values. It is an reference data types not primitives because there are objects and they are being referenced and being changed.

IntByReference

The key knowledge is that this class swaps the orders the two valuues from lowest to highest. It is a reference data type because the data is changed.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * Menu: custom implementation
 * @author     John Mortensen
 *
 * Uses String to contain Title for an Option
 * Uses Runnable to store Class-Method to be run when Title is selected
 */

// The Menu Class has a HashMap of Menu Rows
public class Menu {
    // Format
    // Key {0, 1, 2, ...} created based on order of input menu
    // Value {MenuRow0, MenuRow1, MenuRow2,...} each corresponds to key
    // MenuRow  {<Exit,Noop>, Option1, Option2, ...}
    Map<Integer, MenuRow> menu = new HashMap<>();

    /**
     *  Constructor for Menu,
     *
     * @param  rows,  is the row data for menu.
     */
    public Menu(MenuRow[] rows) {
        int i = 0;
        for (MenuRow row : rows) {
            // Build HashMap for lookup convenience
            menu.put(i++, new MenuRow(row.getTitle(), row.getAction()));
        }
    }

    /**
     *  Get Row from Menu,
     *
     * @param  i,  HashMap key (k)
     *
     * @return  MenuRow, the selected menu
     */
    public MenuRow get(int i) {
        return menu.get(i);
    }

    /**
     *  Iterate through and print rows in HashMap
     */
    public void print() {
        for (Map.Entry<Integer, MenuRow> pair : menu.entrySet()) {
            System.out.println(pair.getKey() + " ==> " + pair.getValue().getTitle());
        }
    }

    /**
     *  To test run Driver
     */
    public static void main(String[] args) {
        Driver.main(args);
    }

}
class MenuRow {
    String title;       // menu item title
    Runnable action;    // menu item action, using Runnable

    /**
     *  Constructor for MenuRow,
     *
     * @param  title,  is the description of the menu item
     * @param  action, is the run-able action for the menu item
     */
    public MenuRow(String title, Runnable action) {
        this.title = title;
        this.action = action;
    }

    /**
     *  Getters
     */
    public String getTitle() {
        return this.title;
    }
    public Runnable getAction() {
        return this.action;
    }

    /**
     *  Runs the action using Runnable (.run)
     */
    public void run() {
        action.run();
    }
}
// The Main Class illustrates initializing and using Menu with Runnable action
class Driver {
    /**
     *  Menu Control Example
     */
    public static void main(String[] args) {
        // Row initialize
        MenuRow[] rows = new MenuRow[]{
            // lambda style, () -> to point to Class.Method
            new MenuRow("Exit", () -> main(null)),
            new MenuRow("Do Nothing", () -> DoNothingByValue.main(null)),
            new MenuRow("Swap if Hi-Low", () -> IntByReference.main(null)),
            new MenuRow("Matrix Reverse", () -> Matrix.main(null)),
            new MenuRow("Diverse Array", () -> Matrix.main(null)),
            new MenuRow("Random Squirrels", () -> Number.main(null))
        };

        // Menu construction
        Menu menu = new Menu(rows);

        // Run menu forever, exit condition contained in loop
        while (true) {
            System.out.println("Hacks Menu:");
            // print rows
            menu.print();

            // Scan for input
            try {
                Scanner scan = new Scanner(System.in);
                int selection = scan.nextInt();

                // menu action
                try {
                    MenuRow row = menu.get(selection);
                    // stop menu
                    if (row.getTitle().equals("Exit")) {
                        if (scan != null) 
                            scan.close();  // scanner resource requires release
                        return;
                    }
                    // run option
                    row.run();
                } catch (Exception e) {
                    System.out.printf("Invalid selection %d\n", selection);
                }

            } catch (Exception e) {
                System.out.println("Not a number");
            }
        }
    }
}
Driver.main(null);
Hacks Menu:
0 ==> Exit
1 ==> Do Nothing
2 ==> Swap if Hi-Low
3 ==> Matrix Reverse
4 ==> Diverse Array
5 ==> Random Squirrels
Squirrels: 7 Days: 11
Squirrels: 7 Days: 19
Squirrels: 10 Days: 15
Squirrels: 13 Days: 12
Squirrels: 15 Days: 16
Squirrels: 15 Days: 18
Squirrels: 20 Days: 14
Squirrels: 20 Days: 17
Squirrels: 22 Days: 13
Squirrels: 30 Days: 10
Total random squirrels: 159, Number of days: 10
Average squirrels per day: 15.9
Hacks Menu:
0 ==> Exit
1 ==> Do Nothing
2 ==> Swap if Hi-Low
3 ==> Matrix Reverse
4 ==> Diverse Array
5 ==> Random Squirrels
public class DoNothingByValue {
    public int[] arr;
    public int val;
    public String word;


    // changed to show what is happening
    public DoNothingByValue (int [] arr, int val, String word) {
        this.arr = new int[5];
        this.val = 0;
        this.word = word.substring(0, 5);

        System.out.print("constructor: ");
        for (int k = 0; k < arr.length; k++) {
            arr[k] = 0;                          // int array is initialized to 0's, not needed
            System.out.print(arr[k] + " ");

        }
        System.out.println(this.word);

    }

    // Local instance variables
    // IntelliJ shows that something is wrong, calling the values passed as parameters as local
    public static void changeIt(int [] arr, int val, String word) {
        arr = new int[5];
        val = 0;
        word = word.substring(0, 5);

        System.out.print("changeIt: "); // added
        for (int k = 0; k < arr.length; k++) {
            arr[k] = 0;
            System.out.print(arr[k] + " "); // added
        }
        System.out.println(word);   // added

    }

    // Variable name are Reference
    // names of variables make no difference, they are just references to addresses
    public static void changeIt2(int [] nums, int value, String name) {
        nums = new int[5];           // new creates new memory address
        value = 0;                   // primitives are pass by value
        name = name.substring(0, 5); // all wrapper classes have automatic "new", same as word = new String(word.substring(0, 5));

        // this loop changes nums locally
        System.out.print("changeIt2: ");
        for (int k = 0; k < nums.length; k++) {
            nums[k] = 0;
            System.out.print(nums[k] + " ");
        }
        System.out.println(name);

    }


    // If you want to change values, think about Return values, but you are limited to one in Java
    // changed to show what is happening
    public static String changeIt3(int [] arr, String word) {
        word = new String(word.substring(0, 5));    // wrapper class does a "new" on any assignment

        System.out.print("changeIt3: ");
        for (int k = 0; k < arr.length; k++) {
            arr[k] = 0;                          // int array is initialized to 0's, not needed
            System.out.print(arr[k] + " ");

        }
        System.out.println(word);

        return word;
    }

    // Variable inside of Object Triple are references
    public static Triple<int[], Integer, String> changeIt4(Triple<int[], Integer, String> T) {
        T.setOne(new int[5]);
        T.setTwo(0);                   // primitives are pass by value
        T.setThree(T.getThree().substring(0, 5)); // all wrapper classes have automatic "new", same as word = new String(word.substring(0, 5));

        // this loop changes nums locally
        System.out.print("changeIt4: ");
        for (int i : T.getOne()) {
            System.out.print(i + " ");
        }
        System.out.println(T.getThree());

        return T;
    }


    // Original method changed to main in order to be a Tester
    public static void main(String[] args) {
        // Does nothing
        int [] nums = {1, 2, 3, 4, 5};
        int value = 6;
        String name = "blackboard";
        System.out.println("Do Nothings");
        // dumb and useless
        changeIt(nums, value, name);
        // dumber and useless
        changeIt2(nums, value, name);
        System.out.print("main: ");
        for (int k = 0; k < nums.length; k++) {
            System.out.print (nums[k] + " ");
        }
        System.out.print(value + " ");
        System.out.print(name);

        System.out.println();
        System.out.println();


        // int[] by reference, return value  -- not complete
        System.out.println("Limited return");
        int[] nums2 = {1, 2, 3, 4, 5};
        value = 6;
        name = "limited";
        name = changeIt3(nums2, name);
        System.out.print("main2: ");
        for (int num : nums2) {
            System.out.print(num + " ");
        }
        System.out.print(value + " ");
        System.out.print(name);

        System.out.println();
        System.out.println();


        // Class/Object
        System.out.println("Do Something with Class");
        int[] nums3 = {1, 2, 3, 4, 5};
        value = 6;
        name = "classy";
        DoNothingByValue doSomething = new DoNothingByValue(nums3, value, name);

        System.out.print("main3: ");
        for (int num : doSomething.arr) {      // should be teaching enhanced for loop on arrays
            System.out.print(num + " ");
        }
        System.out.print(doSomething.val + " ");
        System.out.print(doSomething.word);

        System.out.println();
        System.out.println();

        // Generics
        System.out.println("Do Something with Generics");
        int[] nums4 = {1, 2, 3, 4, 5};
        value = 6;
        name = "generics";
        Triple<int[],Integer,String> tri = changeIt4(new Triple<>(nums4, value, name));

        System.out.print("main: ");
        for (int num : tri.getOne())
            System.out.print (num + " ");

        System.out.print(tri.getTwo() + " ");
        System.out.print(tri.getThree());
    }

}

// This class can be used to pass variables by reference
class Triple<T1, T2, T3> {
    T1 one;
    T2 two;
    T3 three;

    Triple(T1 one, T2 two, T3 three) {
        this.one = one;
        this.two = two;
        this.three = three;
    }

    public T1 getOne() { return this.one; }
    public void setOne(T1 one) { this.one = one; }

    public T2 getTwo() { return this.two; }
    public void setTwo(T2 two) { this.two = two; }

    public T3 getThree() { return this.three; }
    public void setThree(T3 three) { this.three = three; }
}
public class IntByReference {
    private int value;

    public IntByReference(Integer value) {
        this.value = value;
    }

    public String toString() {
        return (String.format("%d", this.value));
    }

    public void swapToLowHighOrder(IntByReference i) {
        if (this.value > i.value) {
            int tmp = this.value;
            this.value = i.value;
            i.value = tmp;
        }
    }

    public static void swapper(int n0, int n1) {
        IntByReference a = new IntByReference(n0);
        IntByReference b = new IntByReference(n1);
        System.out.println("Before: " + a + " " + b);
        a.swapToLowHighOrder(b);  // conditionally build swap method to change values of a, b
        System.out.println("After: " + a + " " + b);
        System.out.println();
    }

    public static void main(String[] ags) {
        IntByReference.swapper(21, 16);
        IntByReference.swapper(16, 21);
        IntByReference.swapper(16, -1);
    }

}
// matrix class is used to store and format the output of a matrix
public class Matrix {
    private final int[][] matrix;

    // store matrix
    public Matrix(int[][] matrix) {
        this.matrix = matrix;
    }

    // nest for loops to format output of a matrix
    public String toString() {
        // construct output of matrix using for loops
        // outer loop for row
        StringBuilder output = new StringBuilder();
        for (int[] row : matrix) {
            // inner loop for column
            for (int cell : row) {
                output.append((cell==-1) ? " " : String.format("%x",cell)).append(" ");
            }
            output.append("\n"); // new line
        }
        return output.toString();
    }

    // print it backwards matrix
    public String reverse() {
        // outer loop starting at end row
        StringBuilder output = new StringBuilder();
        for (int i = matrix.length;  0 < i; i--) {
            // inner loop for column
            for (int j =  matrix[i-1].length; 0 < j; j--) {
                output.append((matrix[i-1][j-1]==-1) ? " " : String.format("%x",matrix[i-1][j-1])).append(" ");
            }
            output.append("\n"); // new line
        }
        return output.toString();
    }

    // declare and initialize a matrix for a keypad
    static int[][] keypad() {
        return new int[][]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, {-1, 0, -1} };
    }

    // declare and initialize a random length arrays
    static int[][] numbers() {
        return new int[][]{ { 0, 1 },
                { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
                { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } };
    }

    // tester method for matrix formatting
    public static void main(String[] args) {
        Matrix m0 = new Matrix(keypad());
        System.out.println("Keypad:");
        System.out.println(m0);
        System.out.println(m0.reverse());


        Matrix m1 = new Matrix(numbers());
        System.out.println("Numbers Systems:");
        System.out.println(m1);
        System.out.println(m1.reverse());

    }

}
import java.util.ArrayList;

// Write a Class Number
public class Number {
    private String title = "Number";
    private String counter = "Index";
    private static int COUNT = 0;
    private final int number;
    private final int index;

    // Number has a zero Argument constructor
    // It initializes a random number between 3 and 36, ie the number of squirrels in class
    public Number() {
        int SIZE = 36; int MIN = 3; int RANGE = SIZE - MIN + 1;  // constants for initialization
        this.number = (int)(Math.random()*RANGE) + MIN;  // observe RANGE calculation and MIN offset
        this.index = Number.COUNT++;    // observe use of Class variable COUNT and post increment
    }

    // It contains a getter for the Random Number
    public int getNumber() {
        return this.number;
    }

    // It contains a getter for Index, or the order it was initialized
    public int getIndex() {
        return this.index;
    }

    // Make a setter to title the Random Number
    public void setTitle(String title) { this.title = title; }

    // Make a setter to name the Counter
    public void setCounter(String counter) { this.counter = counter; }

    // toString method for formatted output, this was not in requirement but is critical knowledge
    public String toString() {
        return this.title + ": " + this.getNumber() + " " + this.counter + ": " + this.getIndex();
    }

    // Write a tester method
    public static void main(String[] args) {

        // Create an ArrayList of Type Number, the ArrayList is called squirrels
        ArrayList<Number> squirrels = new ArrayList<>();

        // Initialize 10 squirrels of class type Number
        // Insert Number Object into ArrayList Squirrels in least to the greatest order using getNumber()
        final int SQUIRRELS = 10;
        for (int i = 0; i < SQUIRRELS; i++) {
            Number num = new Number();
            num.setTitle("Squirrels");
            num.setCounter("Days");
            // Insert in ordered position, this avoids sort algorithm
            for (int j = 0; true; j++) {
                // Conditions to insert
                if ((squirrels.size() == j) // empty or at end of list
                        || (num.getNumber() < squirrels.get(j).getNumber()) )  // less than current
                {
                    /* The java.util.ArrayList.add(int index, Object)
                       method inserts the specified object at the specified position in this list.
                       This is overload of the common java.util.ArrayList.add(Object)
                    */
                    squirrels.add(j, num); // insert in "j" position
                    break;  // break forever loop when inserted
                }
            }
        }

        // Added total/average, not in requirements
        int total = 0;
        for (Number squirrel : squirrels) {
            // Print a formatted message with number of Squirrels and Index
            System.out.println(squirrel);  // prints Object using toString() method
            total += squirrel.getNumber(); // running total, not in requirements
        }
        // Integer division requires cast for precision
        System.out.println("Total random squirrels: " + total + ", Number of days: " + squirrels.size());
        System.out.println("Average squirrels per day: " + total / (double) squirrels.size());
    }

}

2022 FRQ #3

Users of a website are asked to provide a review of the website at the end of each visit. Each review, represented by an object of the Review class, consists of an integer indicating the user’s rating of the website and an optional String comment field. The comment field in a Review object ends with a period ("."), exclamation point ("!"), or letter, or is a String of length 0 if the user did not enter a comment.

public class Review { 
    private int rating; 
    private String comment; 

    /** Precondition: r >= 0 * c is not null. */ 
    public Review(int r, String c) { 
        rating = r; 
        comment = c; 
    } 
    public int getRating() { 
        return rating; 
    } 
    public String getComment() { 
        return comment; 
    } 
    // There may be instance variables, constructors, and methods that are not shown. 
}

The ReviewAnalysis class contains methods used to analyze the reviews provided by users. You will write two methods of the ReviewAnalysis class

public class ReviewAnalysis {
    /** All user reviews to be included in this analysis */ 
    private Review[] allReviews; 

    /** Initializes allReviews to contain all the Review objects to be analyzed */ 
    public ReviewAnalysis() {
         /* implementation not shown */ 
        } 
    
    /** Returns a double representing the average rating of all the Review objects to be * analyzed, as described in part (a) 
     * * Precondition: allReviews contains at least one Review. 
     * * No element of allReviews is null. */ 
    public double getAverageRating() {
         /* to be implemented in part (a) */ 
        } 
    
    /** Returns an ArrayList of String objects containing formatted versions of 
     * * selected user comments, as described in part (b) 
     * * Precondition: allReviews contains at least one Review. * 
     * No element of allReviews is null. * 
     * Postcondition: allReviews is unchanged. */ 
    
    public ArrayList<String> collectComments() {
         /* to be implemented in part (b) */ 
        } 
    }

a. Write the ReviewAnalysis method getAverageRating, which returns the average rating (arithmetic mean) of all elements of allReviews. For example, getAverageRating would return 3.4 if allReviews contained the following Review objects.

public double getAverageRating() {
   // The total amount of each individual reviews

   int reviewTotal = 0;

   // The total amount of reviews in the array allReviews

   int reviewAmount = 0;

   // Loops through every review in the arry allReviews

   for (Review rating : allReviews) {
      // gets the specific rating value and adds it to the total
      reviewTotal = reviewTotal + rating.getRating();

      // add ones to the total amount of reviews
      reviewAmount = reviewAmount + 1;
   }
   

   // creates the average which should be a double since there are decimals needed
   double averageRating = reviewTotal/reviewAmount;
   return averageRating;
}

b. Write the ReviewAnalysis method collectComments, which collects and formats only comments that contain an exclamation point. The method returns an ArrayList of String objects containing copies of user comments from allReviews that contain an exclamation point, formatted as follows. An empty ArrayList is returned if no comment in allReviews contains an exclamation point.

  • The String inserted into the ArrayList to be returned begins with the index of the Review in allReviews.
  • The index is immediately followed by a hyphen ("-").
  • The hyphen is followed by a copy of the original comment.
  • The String must end with either a period or an exclamation point. If the original comment from allReviews does not end in either a period or an exclamation point, a period is added.

The following ArrayList would be returned by a call to collectComments with the given contents of allReviews. The reviews at index 1 and index 4 in allReviews are not included in the ArrayList to return since neither review contains an exclamation point.

Complete method collectComments. /* Returns an ArrayList of String objects containing formatted versions of selected user comments, as described in part (b) Precondition: allReviews contains at least one Review. No element of allReviews is null. Postcondition: allReviews is unchanged. /

public ArrayList<String> collectComments() {
    // arraylist for strings of reviews that are formatted and contain exclaimation points
    ArrayList<String> commentsArray = new ArrayList<String>();

    // loops through each review
    for (Review rating : allReviews) {
        // to keep track of the number that should be in front of the formatted comment
        count = 0;

        // get a comment from allReviews
        String comment = rating.getComment();

        // if there is an index of an ! in the string then it will be counted and make the if conditional true
        if (comment.indexOf("!") >= 0) {
            
            // correct formatting of the comment as a new String
            String newComment = count + "-" + comment;

            //creates lastChar, which stores the last character in the formatted string
            String lastChar = newComment.substring(newComment.length() - 1);

            // checks if there is any punctuation at the end of the string
            if ( (!lastChar.equals("!")) && (!lastChar.equals("."))) {
                // If there is no punctuation then a period is added at the end
                newComment = newComment + ".";

                // adds the comment to the array
                commentsArray.add(newComment);
            }

        }
        count++;
    }    
    return commentsArray;
}

Quiz Corrections

Question Answer I Chose Correct Answer Explanation
9 c e The answer I chose only selects from 0-10 and once multiplied by 6, it only generates values from 0 to 5. This is incorrect because we needed values from 2-12. This question is from Unit 2 and I think I would need to study the built in Math.random() method.
13 b a The answer I chose would be the result if the loop incremented by 1 instead of 3. I got this question wrong because I think I didn't take enough time to look through each line and make notes about what is happening in each loop.
21 d e I knew what the code was doing but I just selected the wrong answer choice.
23 d c I was confused by what the algorithm was doing and selected the wrong choice. This is unit 6 which covers traversing arrays, so I think I need to get better at paying attention to what is happening in each loop.
24 a d I did the opposite of what the question was asking, I picked which option would create a compile0time error instead of which one did.
37 b e I understood this question partially. Again it was another question with a lot of loops, so I needed to pay attention more.