Binary Addition Seed EC

import java.util.Scanner;
public class BinaryAddition {

    public static void main(String[] args) {
        Scanner myObj = new Scanner(System.in);  
        System.out.println("Enter the first number");
        String num1 = myObj.nextLine();
        int number1 = Integer.parseInt(num1);
        System.out.println(num1);

        System.out.println("Enter the second number");
        String num2 = myObj.nextLine();
        int number2 = Integer.parseInt(num2);
        System.out.println(num2);

        //int number1 = 0b1; // binary number 1        0b means that it is a binary number
        //int number2 = 0b1; // binary number 2
        int sum = number1 + number2; // add the binary numbers
        
        // convert the sum to a binary string
        String binarySum = Integer.toBinaryString(sum);
        
        System.out.println("Binary addition of " + number1 + " and " + number2 + " is " + binarySum);
    }
}
BinaryAddition.main(null)
Enter the first number
1
Enter the second number
1
Binary addition of 1 and 1 is 10

Code Exercises

import java.lang.Math;
import java.util.ArrayList;
// int

System.out.println("INT");
int int1 = 4;
int int2 = 5;
int sum = int1 + int2;

System.out.println("int 1 = " + int1);
System.out.println("int 2 = " + int2);
System.out.println("int 1 + int 2 = " + sum);


// double
System.out.println();
System.out.println("DOUBLE");
double a = 12.2;
double b = 2.0;
double multiply = a*b;

System.out.println("double 1 = " + a);
System.out.println("double 2 = " + b);
System.out.println("double 1 * double 2 = " + multiply);


// boolean
System.out.println();
System.out.println("BOOLEAN");
boolean red = true;

if(red){
    System.out.println("The color is red. isRed: " + red);
}
else{
    System.out.println("The color is not red. isRed: " + !red);
}


// char
System.out.println();
System.out.println("CHAR");
char char1, char2, char3;      
char1 = 'Z';
char2 = '*';
char3 = '6';
System.out.println("char1 = Z, char2 = *, char3 = 6");
System.out.println("chars: " + char1 + char2 + char3);


// Wrapper Classes
System.out.println("--------------");
System.out.println("WRAPPER CLASSES");

// Integer
System.out.println("Integer: " + new Integer(sum).toString());

// Double
System.out.println("Double: " + new Double(multiply).toString());

// Boolean
System.out.println("Boolean: " + new Boolean(red).toString());

// Character
System.out.println("Character: " + new Character(char1).toString() + new Character(char2).toString() + new Character(char3).toString());
INT
int 1 = 4
int 2 = 5
int 1 + int 2 = 9

DOUBLE
double 1 = 12.2
double 2 = 2.0
double 1 * double 2 = 24.4

BOOLEAN
The color is red. isRed: true

CHAR
char1 = Z, char2 = *, char3 = 6
chars: Z*6
--------------
WRAPPER CLASSES
Integer: 9
Double: 24.4
Boolean: true
Character: Z*6

Methods and Control Structures

Methods

  • block of code that performs the specfic actions mentioned inside when it is called
  • can include paramters or values into methods
  • designed to be reusable and can be called in different places

Control Structures

  • the "building blocks" of computer programs, control their flow
  • decides if a program takes one path or another, decisions based on conditions
  • program flow is not limited to being linear (can bifurcate, repeat code, or bypass sections)

Teacher Code Exploration

Diverse Array

  • matrix contains methods and control structures
  • multiple methjods and control structures
    • for and while loops
    • if statements
  • data types: int and arrays
// DiverseArray learnings
/* All Array and 2D array questions will have similar patterns
    1. 1D array int[] arr = { 1, 2, 3, 4, 5 }
    2. 2D array int[][] arr2D = { { 1, 2, 3, 4, 5 },
                                  { 2, 3, 4, 5, 6 } }
    3. Arrays dimensions are not mutable, but can be established with variable sizes using "new"
                int[] arr = new int[rows]
                int[][] arr2D = new int[rows][cols]
    4. All iterations can use enhanced or conventional for loops, these apply to both 1D and 2D
                for (int num : arr) { ... }  // enhanced, used when index is not required
                for (int i = 0; i < arr.length; i++) { ... } // conventional, using arr.length to restrict i
    5. Same array comparisons (two indexes), bubble sort like adjacent comparison
                for(int i = 0; i < sumsLength - 1; i++) {  // observe minus
                    for (int j = i + 1; j < sumsLength; j++) { // observe j = i + 1, to offset comparisons
 */

 public class DiverseArray {
    public static int arraySum(int[] arr) {
        int sum = 0;    // sum initializer

        // enhanced for loop as values are needed, not index
        for (int num : arr) {
            sum += num;
            System.out.print(num + "\t");  // debug
        }

        return sum;
    }

    public static int[] rowSums(int[][] arr2D) {
        int rows = arr2D.length;        // remember arrays have length
        int[] sumList = new int[rows];  // size of sumList is based on rows

        // conventional for loop as index used for sumList
        for (int i = 0; i < rows; i++) {
            sumList[i] = arraySum(arr2D[i]);
            System.out.println("= \t" + sumList[i]);  // debug
        }

        return sumList;
    }

    public static boolean isDiverse(int[][] arr2D) {
        int [] sums = rowSums(arr2D);
        int sumsLength = sums.length;

        // ij loop, two indexes needed in evaluation, similar to bubble sort iteration
        for(int i = 0; i < sumsLength - 1; i++) {
            for (int j = i + 1; j < sumsLength; j++) {
                if (sums[i] == sums[j]) {
                    return false;    // leave as soon as you find duplicate
                }
            }
        }
        return true; // all diverse checks have been made
    }

    public static void main(String[] args) {
        int[][] mat1 = {
                { 1, 3, 2, 7, 3 },                       // row 1
                { 10, 10, 4, 6, 2 },                     // row 2
                { 5, 3, 5, 9, 6 },                       // row 3
                { 7, 6, 4, 2, 1 }                        // row 4
        };
        int[][] mat2 = {
                { 1, 1, 5, 3, 4 },                       // row 1
                { 12, 7, 6, 1, 9 },                      // row 2
                { 8, 11, 10, 2, 5 },                     // row 3
                { 3, 2, 3, 0, 6 }                        // row 4
        };

        System.out.println("Mat1 Diverse: " + isDiverse(mat1));
        System.out.println();
        System.out.println("Mat2 Diverse: " + isDiverse(mat2));
    }

}

Random

  • Math.random
  • designed to create a number between 0 and 1
  • to get a numer in a different range, multiple the random number by another number

Do Nothing By Value

  • does not change the values locally. the variable does not actually change because you are only chaning the subvalue
  • changing a varibale happens at the large scale

Int By Reference

  • int changes value even though it is local
  • there is a trick to get around the fact that you can't edit variables locally
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);
    }

}

Menu

  • use try, catch, runnable to control program execution
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);
    }

}

// The MenuRow Class has title and action for individual line item in menu
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("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");
            }
        }
    }
}

2021 FRQ: Methods and Control Structures

public class WordMatch {

    private String secret; // declaring variable secret 

    public WordMatch (String secret) { // constructs WordMatch object with secret string
        this.secret = secret;
    }

    public void setSecret(String secret) { // sets the secret value
        this.secret = secret;
    }

    public int scoreGuess(String guess) { 

        // testing use of control structures which in this case is a for loop
        // make sure that the condition inside the for loop is possible to be executed and has the right condition to make the code function properly

        int count = 0; 

        for (int i = 0; i < secret.length(); i++) { // looping over the whole secret not guess
            if (secret.substring(i).indexOf(guess) == 0) { // start at 0 index and as i increases if index of guess is at the beginning of substring
                count++; // , then increment count by 1 
            }
        }

        return count * guess.length() * guess.length(); // return the score which is how many times guess appeared in secret and multiply by square of length of guess
    }

    public String findBetterGuess (String guess1, String guess2) { 
        
        // this is using the method of scoreGuess above and is inputing guess1 and guess2 into scoreGuess to check which has the higher 
        // this is methods and control structures because the frq is testing that you know when to use and how to call methods to help advance your code and make it function properly

        if (scoreGuess(guess1) > scoreGuess(guess2)) { // if the score of guess1 is greater than score of guess2 
            return guess1; // then guess 1 is the better guess
        }
        if (scoreGuess(guess1) < scoreGuess(guess2)) { // if the score of guess1 is less than score of guess2 
            return guess2; // then guess 2 is the better guess
        }
        if (guess2.compareTo(guess1) > 0) { // compare guess1 and guess2 and the alphabetically greater one is returned
            return guess2;
        }
        return guess1;
    }

    public static void main(String args[]) {  

        Scanner sc = new Scanner(System.in);

        // System.out.println("Enter a guess: ");
        String guess = sc.nextLine();

        String secret = "mississippi";
        WordMatch wordMatch = new WordMatch(secret);

        int score = wordMatch.scoreGuess(guess);
        System.out.println("Score for " + guess + " is " + score);

        // System.out.println("Enter another guess: " +);
        String guess1 = sc.nextLine();

        // System.out.println("Enter another guess: " +);
        String guess2 = sc.nextLine();

        String compare = wordMatch.findBetterGuess(guess1, guess2);
        System.out.println("The better guess between " + guess1 + " and " + guess2 + " is: " + compare);

        sc.close();
    }
}

WordMatch.main(null)
Score for fruit is 0
The better guess is between batch and fluke is: fluke

Wordmatch object constructed with secret String. Then the value of secret is set. Scoreguess is a method that uses a loop to compare the value of guess to the value of secret. Score is incremented for every letter they have in common. In mian, scoreguess is called to get the score for both guesses. Then findBetterGuess compares the two scores and gets the guess with the better score.