Data Type Hacks

Code Examples of Primitive Types and their Wrapper Classes:

int

//primitive 
int[] numbers = {1, 2, 3, 4, 5};
int randomIndex = (int) (Math.random() * numbers.length);
int randomNum = numbers[randomIndex];
System.out.println("Random number from array: " + randomNum);
//wrapper class
Integer[] numbers = {1, 2, 3, 4, 5};
int randomIndex = (int) (Math.random() * numbers.length);
int randomNum = numbers[randomIndex];
System.out.println("Random number from array: " + randomNum);

double

//primitive
double[] prices = {9.99, 19.99, 29.99, 39.99, 49.99};
double totalPrice = 0;
for (double price : prices) {
    totalPrice += price;
}
System.out.println("Total price: " + totalPrice);
//wrapper class
Double[] prices = {9.99, 19.99, 29.99, 39.99, 49.99};
double totalPrice = 0;
for (Double price : prices) {
    totalPrice += price;
}
System.out.println("Total price: " + totalPrice);

boolean

//primitive
boolean[] results = {true, false, false, true, true};
int countTrue = 0;
for (boolean result : results) {
    if (result) {
        countTrue++;
    }
}
System.out.println("Number of true values: " + countTrue);
//wrapper class
Boolean[] results = {true, false, false, true, true};
int countTrue = 0;
for (Boolean result : results) {
    if (result) {
        countTrue++;
    }
}
System.out.println("Number of true values: " + countTrue);

char

//primitive
char[] words = {"apple", "banana", "cherry", "date", "elderberry"};
String randomWord = words[(int) (Math.random() * words.length)];
char firstLetter = randomWord.charAt(0);
System.out.println("Random word: " + randomWord);
System.out.println("First letter: " + firstLetter);
//wrapper class
Character[] words = {'a', 'b', 'c', 'd', 'e'};
char randomWord = words[(int) (Math.random() * words.length)];
char firstLetter = randomWord.charAt(0);
System.out.println("Random word: " + randomWord);
System.out.println("First letter: " + firstLetter);

Key Concepts in Teacher Code

Methods

A method is a block of code that performs a specific task. It can take input parameters and return a value. In the methodsDataTypes code, there are several methods that perform different tasks, such as finding the maximum value in an array, converting a temperature between Celsius and Fahrenheit, and checking if a number is prime.

Control Structures

Control structures are statements that control the flow of execution in a program. The most common control structures are if/else statements, loops, and switch statements. In the methodsDataTypes code, there are several examples of control structures, such as for loops used to iterate over arrays, and if/else statements used to check conditions and control program flow.

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

This code defines a custom implementation of a menu, which is used to allow the user to select from a list of options. The options are defined as instances of the MenuRow class, which contains a title and an action. The title is a description of the option that is displayed to the user, and the action is a Runnable that is executed when the user selects the option.

The Menu class contains a HashMap that maps integer keys to MenuRow values. Each key corresponds to a menu option, and each value contains the title and action for that option. The Menu class has a constructor that takes an array of MenuRow instances and uses them to populate the HashMap.

The Menu class also contains methods to get a MenuRow by key, iterate through and print the options in the menu, and a main method that can be used to test the menu.

The MenuRow class contains a constructor that takes a title and a Runnable action, as well as getters for the title and action. The MenuRow class also contains a run method that executes the action by calling its run method.

The Driver class contains a main method that creates an array of MenuRow instances and uses them to create a Menu. It then enters a loop that displays the menu and waits for the user to select an option. When the user selects an option, the corresponding Runnable is executed.

Key Concepts

DoNothingByValue - This class demonstrates that primitive types are passed by value in Java. This means that changes made to the parameter inside the method do not affect the original variable outside of the method.

  • IntByReference - This class demonstrates how to simulate pass by reference in Java using an object. By passing an object reference instead of a primitive type, changes made to the object inside the method are reflected outside of the method.

  • Menu - This class demonstrates the use of try/catch blocks to handle exceptions and the implementation of a menu system using a switch statement. The Runnable interface is also used to allow for concurrent execution of the menu and the main program.

  • DiverseArrays - This class demonstrates the use of arrays to store data and the implementation of several methods to manipulate and access array elements. It also demonstrates the use of nested loops to iterate over multi-dimensional arrays.

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
}

This code defines a method called "isDiverse" that takes a 2D integer array as an argument and returns a boolean value. It calculates the sums of each row of the input array, and then checks if any of these sums are equal to each other. If any sums are equal, the method returns false, and if all sums are unique, the method returns true.