Code Exercise Examples

import java.lang.Math;
import java.util.ArrayList;
// int
System.out.println("--------------");
System.out.println("integer:");
int[] intArray = new int[5];
int sum = 0;
for (int i = 0; i < intArray.length; i++) {
    intArray[i] = (int) (Math.floor(Math.random() * 100));
    System.out.println("num" + i + ": " + intArray[i]);
    sum += intArray[i];
}

System.out.println("Sum: " + sum);
System.out.println("--------------");

// double
System.out.println("--------------");
System.out.println("double:");
double double1 = 10.0;
double double2 = 3.0;
double ratio = double1/double2;

System.out.println("double1: " + double1);
System.out.println("double1: " + double2);
System.out.println("double1 / double2: " + ratio);
System.out.println("--------------");

// boolean
System.out.println("--------------");
System.out.println("boolean:");
boolean smelly = true;

if(smelly){System.out.println("Ew you're smelly! Smelly: " + smelly + "Go take a shower!");}
else{System.out.println("Good Job! Clean: " + !smelly);}
System.out.println("--------------");

// char
System.out.println("--------------");
System.out.println("char:");
char c1, c2, c3;      
// 65 & 67 are ASCII codes
c1 = 65;
c2 = 'B';
c3 = 67;
System.out.println("c1 = 65; c2 = 'B'; c3 = 67;");
System.out.println("The characters are: " + c1 + c2 + c3);
System.out.println("--------------");


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

// Integer
ArrayList<Integer> intArrayList = new ArrayList<>();
for (int i : intArray){
    intArrayList.add(new Integer(i));
}

System.out.println("intArrayList: " + intArrayList.toString());


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

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

// Character
System.out.println("Character: " + new Character(c1).toString() + new Character(c2).toString() + new Character(c3).toString());
--------------
integer:
num0: 99
num1: 54
num2: 46
num3: 97
num4: 68
Sum: 364
--------------
--------------
double:
double1: 10.0
double1: 3.0
double1 / double2: 3.3333333333333335
--------------
--------------
boolean:
Ew you're smelly! Smelly: trueGo take a shower!
--------------
--------------
char:
c1 = 65; c2 = 'B'; c3 = 67;
The characters are: ABC
--------------
--------------
Wrapper Classes:
intArrayList: [99, 54, 46, 97, 68]
Double: 3.3333333333333335
Boolean: true
Character: ABC

Methods and Control Structures

Methods

  • A method in Java is a block of code that, when called, performs specific actions mentioned in it.
  • For instance, if you have written instructions to draw a circle in the method, it will do that task.
  • You can insert values or parameters into methods, and they will only be executed when called.
  • A method is similar to a function in other programming languages such as python

Control Structures

  • Control Structures can be considered as the building blocks of computer programs.
  • They are commands that enable a program to “take decisions”, following one path or another.
  • A program is usually not limited to a linear sequence of instructions since during its process it may bifurcate, repeat code or bypass sections.

APCSA FRQ 2017 Methods and Control Structures

- https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-frq-2017.pdf

Exploring teacher code

Diverse Array
  • Checks if the sums of each row in a 2d array are all different (diverse)
  • Returns true if this is true, returns false if not
  • Starts by summing arrays then returns that sums into single arrray ##### Matric
  • Contains methods and control structures
  • Multiple methods that allow stuff to happen
  • Multiple control structures

    • Loops
      • For
      • While
    • If statements
  • Fits within data types because contains arrays which is a data type

  • Takeaway: most code segments no matter what they are on have to do with methods and control structures

Random

  • Math.random
  • Gives value between 0 and 1
  • To get a random value between 7 and 9, double a Math.random value and add 7 to it

Do nothing by value

  • You're basically changing a variable but the variable doesn't actually change because it is changing the subvalue and not the actual value
  • Changing a variable only happens at a large scale
    • Can't do it locally

Int by Reference

  • The int changes its value even though you are doing it locally
  • Basically says theres a way to get around the fact that you cant edit variables locally
  • Try, Catch, Runnable are used to control program execution
package com.nighthawk.hacks.methodsDataTypes;

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("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");
            }
        }
    }

Method and Control Structures

  • There are three kinds of control structures: Conditional Branches, which we use for choosing between two or more paths. There are three types in Java: if/else/else if, ternary operator and switch. Loops that are used to iterate through multiple values/objects and repeatedly run specific code blocks.

  • MenuRow and Runnable are data types and also control structures

Exploring AP Classroom

public class FrogSimulation
{
    /** Distance, in inches, from the starting position to the goal. */
    private int goalDistance;

    /** Maximum number of hops allowed to reach the goal. */
    private int maxHops;

    /** Constructs a FrogSimulation where dist is the distance, in inches, from the starting
    * position to the goal, and numHops is the maximum number of hops allowed to reach the goal.
    * Precondition: dist > 0; numHops > 0
    */
    public FrogSimulation(int dist, int numHops)
    {
    goalDistance = dist;
    maxHops = numHops;
    }

    /** Returns an integer representing the distance, in inches, to be moved when the frog hops.
     */
    private int hopDistance()
    { /* implementation not shown */ 

        // Int datatype used because steps should be whole numbers
        return (int) (Math.random() * 20) - 10;
    }

    /** Simulates a frog attempting to reach the goal as described in part (a).
    * Returns true if the frog successfully reached or passed the goal during the simulation;
    * false otherwise.
    */
    public boolean simulate()
    { /* to be implemented in part (a) */ 
        int distance = 0;

        // if control structures catch any return conditions being met
        for (int i = 0; i < maxHops; i++) {
            distance += hopDistance();
            if (distance < 0) {
                return false;
            }
            if (distance >= goalDistance) {
                return true;
            }
        }
        return false;
    }

    /** Runs num simulations and returns the proportion of simulations in which the frog
    * successfully reached or passed the goal.
    * Precondition: num > 0
    */
    public double runSimulations(int num)
    { /* to be implemented in part (b) */ 

        // Note the usage of the double datatype here
        // When doubles are operated on with ints, the result is an integer
        double trueResults = 0;


        for (int i = 0; i < num; i++) {

            // if control structure differentiates between successful and unsuccessful simulations
            if (this.simulate()) {
                trueResults++;
            }
        }

        // Here a double and int are operated on together, resulting in another double
        return trueResults / num;
    }

    public static void main(String[] args) {
        FrogSimulation test = new FrogSimulation(24, 5);
        System.out.println(test.simulate());

        System.out.println(test.runSimulations(100));
    }
} 

FrogSimulation.main(null);
false
0.0

Data Types

There are 2 main datatypes present in the above code, which are:

  • ints
  • doubles

Certain datatypes are better suited than others to model a situation; since the situation includes the distance per hop, the maximum distance, and the max number of hops are all whole numbers, ints are preferrable to use here.

However, considering the output of runSimulations() being a ratio, a different datatype would be better suited: a double.

Methods and Control Structures

Control structures form the building blocks of most methods, allowing them to handle simple tasks such as filtering or calculating. In this case, the main methods are simulate() and runSimulations().

simulate() utilizes both for loops, in order to iterate through the hops and their effect on distance, and if loops, in order to check if any one of the return conditions are met (negative distance, max hops, or reached distance).

runSimulations() also takes advantage of for loops in order to run simulate() numerous times, using an if statement to distinguish between successful and unsuccessful simulations.