Tech Talk 1
Tech Talk 1 stuff
- Notes
- Binary Addition
- Overall Score
- Code Problems
- Methods and Control Structures
- Exploring Teacher Code
- Exploring Menu
- Exploring FRQ
- A reference is a pointer that points to the memory location for primitive data
- Wrapper class is Integer for an int and Double for a double and so on
import java.util.Scanner;
public class BinaryAddition {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first binary number: ");
String binary1 = scanner.nextLine();
System.out.print(binary1 + "\n");
System.out.print("Enter the second binary number: ");
String binary2 = scanner.nextLine();
System.out.print(binary2 + "\n");
int decimal1=Integer.parseInt(binary1,2);
int decimal2=Integer.parseInt(binary2,2);
int sum = decimal1 + decimal2;
System.out.println(Integer.toBinaryString(sum));
}
}
BinaryAddition.main(null);
import java.lang.Math;
import java.util.ArrayList;
System.out.println("integer arary");
int[] array = new int[5];
int total = 0;
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10);
System.out.println("Number at index " + i + " is " + array[i]);
total += array[i];
}
System.out.println("The total is " + total);
System.out.println("doubles");
double uno = Math.random() * 10;
double dos = Math.random() * 10;
double div = dos / uno;
System.out.println("uno: " + uno);
System.out.println("dos: " + dos);
System.out.println("div: " + div);
System.out.println("Booleans");
boolean bool = true;
boolean bool2 = false;
if (bool == bool2) {
System.out.println("true");
} else {
System.out.println("false");
}
System.out.println("Characters");
char char1 = 'a';
char char2 = 'b';
System.out.println("All the characters are " + char1 + char2);
System.out.println("Wrapper");
Integer wrapper = new Integer(5);
System.out.println("Wrapper of Integer: " + wrapper);
ArrayList<Integer> yo = new ArrayList<>();
for (int i : array){
yo.add(new Integer(i));
}
System.out.println("arraylist yo: " + yo.toString());
Methods
- A method is a block of code that performs a specific task.
- Methods are used to contain a specific functionality of a program.
- Methods can be called from other parts of a program to execute the code inside the method. (Similar to a function)
Control Structures
- Control structures are used to control the flow of a program.
- Control structures are used to alter the flow of a program.
- Control structures are used to make decisions in a program.
Exploring Teacher Code
- DiverseArray has methods and control structures. Each method have their own parameters and do diffrent logical operations to the parameters. This is the same with the Matrix class as well
- DiverseArray and Matrix classes exclusively employ primitive types without any wrapper classes. Nevertheless, they do include 2D arrays for these primitives and a String[] which is a reference type. While the String[] is a reference type, the primitives are not. Similarly, the 2D arrays are reference types, but their elements are primitives. The primitives are stored within the 2D arrays, whereas the 2D arrays themselves are stored as elements within the reference type of the String[].
- DoNothingByValue is also a method but it just takes the primitive and does nothing to it. It does not alter the value of the primitive. It copies the primitive.
- IntByReference takes the reference of the integer and is able to modify it.
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
public 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
public 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");
}
}
}
}
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;
public FrogSimulation(int dist, int numHops)
{
goalDistance = dist;
maxHops = numHops;
}
private int hopDistance()
{ /* implementation not shown */
// Int datatype used because steps should be whole numbers
return (int) (Math.random() * 20) - 10;
}
public boolean simulate() {
int start = 0;
int numOfHops = 0;
// control structure to simulate frog hopping with constraints
while(start >= 0 && numOfHops < maxHops && start < goalDistance) {
start += hopDistance();
numOfHops++;
}
return start >= goalDistance;
}
public double runSimulations(int num) {
int count = 0;
for (int i = 0; i < num; i++) {
// control structure to count number of successful simulations
if (this.simulate() == true) {
count++;
}
}
// Cast to double to get decimal value
return (double) count / num;
}
public static void main(String[] args) {
FrogSimulation test = new FrogSimulation(20, 5);
System.out.println(test.simulate());
System.out.println(test.runSimulations(100));
}
}
FrogSimulation.main(null);