What are Methods and Control Structures?

Methods and control structures are important programming concepts used to organize and control the flow of code execution in a program.

Methods are reusable blocks of code that perform specific tasks. They allow you to encapsulate functionality and reuse it throughout your code. Methods can take inputs, perform operations on those inputs, and return outputs. Methods are often used to break down a large problem into smaller, more manageable parts.

Control structures, on the other hand, determine the order in which code is executed. They allow you to control the flow of execution based on certain conditions. Control structures include if/else statements, loops, and switch statements.

If/else statements allow you to execute code based on whether a certain condition is true or false. Loops allow you to repeat code a certain number of times or until a certain condition is met. Switch statements allow you to choose between multiple possible code paths based on the value of a variable.


Diverse Arrays

  • The Diverse Arrays shown in Teacher's code does fit the guidelines for being methods and control structures, and it also fits the interpretation of being data types.

DoNothingByValue

  • This code utilizes a newly initialized array with a for loop to print out a specific word using the array length, while increasing by 1 each loop.

IntByReference

  • This code prints out before and after values, while changing them utilizing a swapper function created by swapping two variables.

Instances of MenuRow and Runnable are control structures, as they determine which code is going to be run.

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

}
IntByReference.main(null);
Before: 21 16
After: 16 21

Before: 16 21
After: 16 21

Before: 16 -1
After: -1 16

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * MENU CODE HERE
 * 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");
            }
        }
    }
}
// AP FRQ Methods and Control Structures
public class WordMatch {
    private String s1;
    private String s2;

    public WordMatch(String s1, String s2) {
        this.s1 = s1;
        this.s2 = s2;
    }

    public int countMatchingChars() {
        if (s1.length() != s2.length()) {
            return -1;
        }
        int count = 0;
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) == s2.charAt(i)) {
                count++;
            }
        }
        return count;
    }

    public void printMatchingChars() {
        if (s1.length() != s2.length()) {
            System.out.println("The two strings are not the same length.");
            return;
        }
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) == s2.charAt(i)) {
                System.out.println(s1.charAt(i));
            }
        }
    }

    public void scoreGuess(String guess){
        int length2 = secret.length();
        char c = 'i';
        int count = 0;
        for (int i = 0; i < secret.length(); i++) {
            if (secret.charAt(i) == c) {
                count++;
            }
    }
        int score = length2*length2*sub;
        return score;
    }

    public static void main(String[] args) {
        WordMatch wm = new WordMatch("hello", "world");
        int count = wm.countMatchingChars();
        System.out.println("Number of matching characters: " + count);
        System.out.println("Matching characters:");
        wm.printMatchingChars();
    }
}