Data Types Hacks
Notes, Hacks, and HW for Data Types.
- Binary Addition Seed
- int/Integer
- double/Double
- boolean/Boolean
- char/Character
- Methods and Control Structure FRQ: 2016 Q1
- Explore Teacher Code
import java.util.*;
public class BinaryAddition {
static Scanner sc = new Scanner(System.in);
public static int inputBinary (String prompt) {
System.out.print(prompt);
int deciOne = sc.nextInt();
System.out.println(deciOne);
int binOne = 0;
for (int i = 10; i>=0; i--) {
binOne += (int)((deciOne % Math.pow(10,i+1)) / Math.pow(10,i)) * (Math.pow(2,i));
}
return binOne;
}
public static String addBin (int numOne, int numTwo) {
String sum = "";
int carryOver = 0;
for (int i = 0; i<=33; i++) {
int first = numOne % 2;
int second = numTwo % 2;
if (first + second + carryOver > 1) {
sum = (char)('0' + (first + second + carryOver - 2)) + sum;
carryOver = 1;
}
else {
sum = Integer.toString(first + second + carryOver) + sum;
carryOver = 0;
}
numOne = numOne >> 1;
numTwo = numTwo >> 1;
}
// cut string
while (sum.charAt(0) == '0' && sum.length() > 1) {
sum = sum.substring(1, sum.length());
}
return sum;
}
public static void main (String[] args) {
int numOne = inputBinary("Input first binary number: ");
int numTwo = inputBinary("Input second binary number: ");
String sum = addBin(numOne, numTwo);
System.out.println("The sum is: " + sum);
}
}
BinaryAddition.main(null);
void swap (int a, int b) {
int temp = a;
a = b;
b = temp;
}
int a = (int)(Math.random()*100);
int b = (int)(Math.random()*100);
System.out.println("a = " + a + " and " + "b = " + b);
swap(a, b);
// values stay the same
System.out.println("a = " + a + " and " + "b = " + b);
int c = a + b;
System.out.println("c = " + c);
void swap (Integer a, Integer b) {
Integer temp = a;
a = b;
b = temp;
}
Integer a = new Integer((int)(Math.random()*100));
Integer b = (int)(Math.random()*100);
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(a);
arr.add(b);
System.out.println("arr (1st) = " + arr.get(0) + " and " + "arr (2nd) = " + arr.get(1));
swap(arr.get(0), arr.get(1));
// values stay the same
System.out.println("arr (1st) = " + arr.get(0) + " and " + " arr (2nd) = " + arr.get(1));
Integer c = a + b;
System.out.println("c = " + c);
void swap (double a, double b) {
double temp = a;
a = b;
b = temp;
}
double a = Math.random();
double b = Math.random();
System.out.println("a = " + a + " and " + "b = " + b);
swap(a, b);
// values stay the same
System.out.println("a = " + a + " and " + "b = " + b);
double c = a + b;
System.out.println("c = " + c);
void swap (Double a, Double b) {
Double temp = a;
a = b;
b = temp;
}
Double a = new Double(Math.random());
Double b = new Double(Math.random());
ArrayList<Double> arr = new ArrayList<>();
arr.add(a);
arr.add(b);
System.out.println("arr (1st) = " + arr.get(0) + " and " + "arr (2nd) = " + arr.get(1));
swap(arr.get(0), arr.get(1));
// values stay the same
System.out.println("arr (1st) = " + arr.get(0) + " and " + "arr (2nd) = " + arr.get(1));
double c = a + b;
System.out.println("c = " + c);
void swap (boolean a, boolean b) {
boolean temp = a;
a = b;
b = temp;
}
boolean a = true;
boolean b = false;
System.out.println("a = " + a + " and " + "b = " + b);
swap(a, b);
// values stay the same
System.out.println("a = " + a + " and " + "b = " + b);
boolean c = a || b;
System.out.println("c = " + c);
void swap (Boolean a, Boolean b) {
Boolean temp = a;
a = b;
b = temp;
}
Boolean a = true;
Boolean b = false;
ArrayList<Boolean> arr = new ArrayList<>();
arr.add(a);
arr.add(b);
System.out.println("arr (1st) = " + arr.get(0) + " and " + "arr (2nd) = " + arr.get(1));
swap(arr.get(0), arr.get(1));
// values stay the same
System.out.println("arr (1st) = " + arr.get(0) + " and " + "arr (2nd) = " + arr.get(1));
boolean c = a || b;
System.out.println("c = " + c);
void swapCh (char a, char b) {
char temp = a;
a = b;
b = temp;
}
char a = 'a';
char b = 'b';
System.out.println("a = " + a + " and " + "b = " + b);
swapCh(a, b);
// values stay the same
System.out.println("a = " + a + " and " + "b = " + b);
char[] c = {a, b};
String str = new String(c);
System.out.println("str = " + str);
System.out.println("str substring 0 to 1 = " + str.substring(0,1));
void swapCh (Character a, Character b) {
Character temp = a;
a = b;
b = temp;
}
Character a = new Character('a');
Character b = new Character('b');
ArrayList<Character> arr = new ArrayList<>();
arr.add(a);
arr.add(b);
System.out.println("arr (1st) = " + arr.get(0) + " and " + "arr (2nd) = " + arr.get(1));
swapCh(arr.get(0), arr.get(1));
// values stay the same
System.out.println("arr (1st) = " + arr.get(0) + " and " + "arr (2nd) = " + arr.get(1));
char[] c = new char[arr.size()];
for (int i = 0; i<arr.size(); i++) {
c[i] = arr.get(i);
}
String str = new String(c);
System.out.println("str = " + str);
System.out.println("str substring 0 to 1 = " + str.substring(0,1));
Methods and Control Structure FRQ: 2016 Q1
- RandomStringChooser class
a.
Write the RandomStringChooser class. The constructor accepts an array of strings as a parameter and stores the array in an instance variable. The class should also have a method called getNext that returns a random string from the array. If all the strings have been returned, then the method should return "NONE". The method should not return the same string twice.
String[] words = {"wheels", "on", "the", "bus"};
RandomStringChooser chooser = new RandomStringChooser(words);
for (int k = 0; k < 6; k++)
{
System.out.print(chooser.getNext() + " ");
}
// output: bus the wheels on NONE NONE
public class RandomStringChooser {
// declare the instance variable
private ArrayList<String> words;
// write the constructor
public RandomStringChooser(String[] wordArray)
{
// initialize the instance variable with for loop
words = new ArrayList<String>();
for (String word : wordArray)
{
words.add(word);
}
}
// get random word from array if there is any
public String getNext() {
if (words.size() > 0) {
return words.remove((int)(Math.random() * words.size()));
}
return "NONE";
}
// tester method
public static void main(String[] args) {
String[] words = {"wheels", "on", "the", "bus"};
RandomStringChooser chooser = new RandomStringChooser(words);
for (int k = 0; k < 6; k++)
{
System.out.print(chooser.getNext() + " ");
}
}
}
RandomStringChooser.main(null);
A breakdown
Theres the normal class description and boilerplate code, but the important part is the constructor. The constructor takes in an array of strings and stores it in an instance variable. The instance variable is an array of strings, so it can be used in the other methods.
The method getNext() returns a random string from the array. The method should not return the same string twice. This means that the method should remove the string from the array after it is returned. This is a little tricky, but we can use the ArrayList class to help us out. The ArrayList class is a resizable array, also a complex data type, which means that we can add and remove elements from the array. We can use the ArrayList class to store the strings from the array, and then use the ArrayList class to remove the strings after they are returned. The remove() method takes in an index as a parameter, so we can use the Random class to generate a random index and multiply by the data size to get some number between 0 and the size of the array. However, the random class returns a double, so we need to cast it into an int, which is a primitive data type. This is passed by value into the remove method.
Now we can use it as the index for the remove() method. The remove() method returns the element that was removed, so we can return it from the getNext() method while simultaneously printing out the element removed.
As seen with the output, there are two NONES because of it choosing 6 out of 4 words.
B
RandomLetterChooser subclass. It constructs a random letter chooser given a string of str, implementing getSingleLetters that returns an array of single-letter strings. The constructor should call the superclass constructor with the array of single-letter strings.
public class RandomLetterChooser extends RandomStringChooser {
public RandomLetterChooser(String str) {
super(getSingleLetters(str));
}
private static String[] getSingleLetters(String str) {
String[] letters = new String[str.length()];
for (int i = 0; i < str.length(); i++) {
letters[i] = str.substring(i, i + 1);
}
return letters;
}
public static void main(String[] args) {
RandomLetterChooser chooser = new RandomLetterChooser("cat");
for (int k = 0; k < 4; k++)
{
System.out.print(chooser.getNext());
}
}
}
RandomLetterChooser.main(null);
B Breakdown
Essentially, this is the exact thing as RandomWordChooser, but instead of an array of words, its an array of strings. So, we can just extend the method of getNext() from the RandomWordChooser class and just change the array of words to an array of strings. The constructor essentially does this, by calling the super constructor with the array of single-letter strings generated with the getSingleLetters method. These get passed by value, and even though the actual array isn't actually stored, the array doesn't get changed.
the getSingleLetters wasn't part of the FRQ, but it was quick to code. It just splits the string into an array of single-letter strings with the substring method.
Explore Teacher Code
What are Methods and Control Structures?
Methods and Control Structures, in the context of AP Classroom, is the process of creating classes and methods to solve problems. The methods and control structures are the building blocks of the Java programming language.
ChatGPT: Methods: Methods are also known as functions or procedures in different programming languages. They are a set of statements or code blocks that are executed together to perform a specific task. Methods can take input arguments and return output values or perform a set of actions without returning any value. They are typically designed to be reusable and modular, allowing the same code to be called from different parts of a program.
Control Structures: Control structures are constructs in programming languages that allow the flow of code to be controlled based on specific conditions or events. They include conditional statements, loops, and branching statements.
Conditional statements (if/else statements) allow the program to make decisions based on specific conditions, executing one block of code if the condition is true and another block if the condition is false. Loops (for loops, while loops) allow the program to repeat a set of actions multiple times until a specific condition is met. Branching statements (break, continue) allow the program to exit out of a loop or skip certain iterations based on specific conditions. Control structures are used to make programs more efficient and flexible, allowing them to handle different scenarios and inputs.
Especially on the test, students will be asked to write program code to create objects of a class and call methods, and satisfy method specifications.
Diverse Arrays and Matrix
Basically this code takes in a 2D array, and checks if it is diverse if the sums of each row are different.
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 is kind of like Methods and Control Structures, as it is a method that takes in parameters and meets specificatiosn. It has control structures like conditionals and loops, but it is not an object.
As for Data Types, I think it has some usage of int arrays, but they are all passed as reference as the primitive class.
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();
}
}
This code definitely exhibits methods and control structures, with methods like toString and reverse being able to print out the 2D integer arrays. These are designed to specification with for loops and conditionals.
It also has more data types, with actual 2D integera arrays being stored inside functions. These can be seen to be passed by reference, so the actual array does not get changed when the code is run.
Review other code:
DoNothingByValue This code mostly demosnstrates passing variables as reference, with the Triple class defining specific wrapper classes. There are multiple changeIt methods, which change the value of the variable. The changeIt method with the primitive data type is passed by value, so the actual value of the variable does not change. The changeIt method with the wrapper class is passed by reference, so the actual value of the variable does change.
IntByReference The key knowledge here is that you can swap orders by assigning it to a temporary memory address for both to access and swap. In addition, since these integers are stored in the actual object istelf, the values are passed by reference, so the actual values of the variables change.
Menu code
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");
}
}
}
}
Control structurs in Drive:
- while
- try/catch
- if/else
MenuRow: There are data types of String as a class, not a primitive, but realistically it doesn't show much there or even in methods/control structures
Runnable: In Java, "runnable" refers to a type of object that can be executed by a thread. Specifically, a "runnable" object is one that implements the java.lang.Runnable interface, which has a single method named run().
The run() method contains the code that will be executed when the thread is started. To create a new thread that runs a Runnable object, you can create an instance of the Thread class and pass the Runnable object to its constructor: