Data Structures
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
Exploring teacher code
Diverse Array & Matrix
- Contains methods and control structures
- Multiple methods that allow stuff to happen
-
Multiple control structures
- Loops
- For
- While
- If statements
- Loops
-
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
Menu
- 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