Methods and Control Structures
Control Structures
- They are commands that enable a program to “take decisions”, following one path or another
- Basic control strucutres: Conditional- used to execute one or more statements if a condition is met, Loops- which purpose is to repeat a statement a certain number of times or while a condition is fulfilled
- Examples in Diverse Array: for loops and if conditionals
Methods
- a collection of statements that perform some specific task and return the result to the caller
- A Java method can perform some specific task without returning anything
- Methods in Java allow us to reuse the code without retyping the code
- every method must be part of some class
6 components of method declaration
- modifier (public, private, protected, default)
- return type (void)
- parameter list
- exception list
- method body (where the code goes)
Types of methods
- predifined method = already defined in some java calss library
- user-defined method = written by the programmer where we modify
Naming
- first word is lower case verb
- second word followed by adjective or noub
- ie: findSum
seen in code?
- methods are seen throughout the diverse array and matrix code, and encapsulate
Questions
Look at Diverse Arrays, Matrix in Teacher code and see if you think this is Methods and Control structures.
- I think these are methods and control structures because there are methdos seen throughout the code that pass params and return information. Look at Diverse Arrays,Matrix in Teacher code an see if you thing this fits Data Types.
- There are primtives that can be seen in both diverse arrays and matrix, such as int. Review DoNothingByValue, what is key knowledge here?
- The actual value of the variable is not changing, but instead the sub value is
- You can not change a variable locally-- a copy is made Review IntByReference, what is key knowledge here?
- Passes integer values by reference
- Allows for a way around not being able to change a variable locally
- Changes made to the value within method or function are shown outside of the method or function
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; }
}
// 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));
}
}
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.HashMap;
import java.util.Map;
import java.util.Scanner;
// 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();
}
}
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 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");
}
}
}
}
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");
}
}
}
}
Menu follow up
Define "Method and Control Structures". To the Teacher, the Menu Code has the most work of methodDataTypes files that is related to the "Methods and Control Structures" topic. Such exploration would begin by asking "describe Java Methods and Control structures". Are instances of MenuRow and Runnable data types, control structures? Does Driver have control structures, enumerate them.
- Instances of MenuRow and Runnable data types are control strucutres because they are what is controlling the code, and having it pass through different statements and conditionals in order for it to meet the requirments needed and continue to run
- Driver has control structures such as the if conditional, while loop, and the catch exceptions.