Data Types
Learning the different types of data
- Early Seed Award: write java code that performs binary addition of 1+1
- Small Code Exercises
- Methods and Control Structures
- Exploring Mr. M's code
- Exploring 2017 FRQ
import java.util.Scanner;
public class BinaryAddition {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the first binary number: \n ");
int binary1 = input.nextInt(2); // Read binary input as base-2 integer
System.out.print("Enter the second binary number: \n ");
int binary2 = input.nextInt(2); // Read binary input as base-2 integer
int sum = binary1 + binary2;
// Binary representation of sum
String binarySum = Integer.toBinaryString(sum); // this method returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.
// Output the result
System.out.println(binary1 + " + " + binary2 + " = " + binarySum);
}
}
BinaryAddition.main(null);
Small Code Exercises
Instructions: Write a Jupyter notebook code example on the following primitive types with a code example (4 to 5 lines), preference would be using array and methods like substring and random as applicable: int, double, boolean, char. Now convert each of the examples to corresponding Wrapper classes, using arrays.
/// Primitive Data Type "int" within an array
public class Example {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10}; // define array called numbers that have 5 int values
int sum = 0;
for (int i = 0; i < numbers.length; i++) { // iterate over array to sum the int values
sum += numbers[i];
}
System.out.println("Sum of numbers: " + sum); // outputs the sum
}
}
Example.main(null);
/// Primitive Data Type "double" within an array
public class DoubleArrayExample {
public static void main(String[] args) {
// declare an array of doubles
double[] myArray = { 3.14, 2.718, 1.618, 0.707 }; // declare an array with 4 values
// print out the values of the array
for (int i = 0; i < myArray.length; i++) {
System.out.println("Element " + i + " = " + myArray[i]); // loop through the array using a for loop and print out each element in the array. Note that we use the double primitive type to declare the array and assign values to it.
}
}
}
DoubleArrayExample.main(null);
/// Primitive Data Type "boolean" within an array
public class BooleanArrayExample {
public static void main(String[] args) {
// declare an array of booleans
boolean[] myArray = { true, false, true, false }; // declare array with boolean data types
// print out the values of the array
for (int i = 0; i < myArray.length; i++) {
System.out.println("Element " + i + " = " + myArray[i]);
}
}
}
BooleanArrayExample.main(null);
/// Primitive Data Type "char" without array
import java.util.Random;
public class CharExample {
public static void main(String[] args) {
Random rand = new Random(); // create random object to generate random number
char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // array of vowels
char randomVowel = vowels[rand.nextInt(vowels.length)]; // next Int method of the rand object generates a random integer that retrieves a random vowel
System.out.println("The random vowel is " + randomVowel);
}
}
CharExample.main(null);
/// Primitive Data Type "char" with an array
public class CharArrayExample {
public static void main(String[] args) {
// declare an array of chars
char[] myArray = { 'a', 'b', 'c', 'd' };
// print out the values of the array
for (int i = 0; i < myArray.length; i++) {
System.out.println("Element " + i + " = " + myArray[i]);
}
}
}
CharExample.main(null);
Methods and Control Structures
- What are methods?
- A method in Java is a block of code that, when called, performs specific actions mentioned in it.
- Think of a method as a subprogram that acts on data and may, or may not, return a value. Each method has its own name.
- What are control structures?
- A control structure is a block of code that can change the path we take through those instructions. Three types: conditional branches, loops, and branching statements
- Inside methods most of the time
- Conditional statements: Execute a certain block of code only if a particular condition is met. Examples: "if" statement, the "else" statement, and the "switch" statement.
- Looping Statements: for loop, while loop, do while loops
- Jump statements: "break" statement, the "continue" statement, and the "return" statement.
- Java provides Control structures that can change the path of execution and control the execution of instructions.
- What FRQ did you explore?
- Explored 2018 FRQ 1. Click here
Looping statements: These are used to repeat a block of code until a particular condition is met. Examples include the "for" loop, the "while" loop, and the "do-while" loop. Jump statements: These are used to transfer control to another part of the program. Examples include the "break" statement, the "continue" statement, and the "return" statement.
Exploring Mr. M's code
- Diverse Array
- Matric has methods and control structures
- It has loops and if statements
- Has data types because it uses int and arrays Methods like arraySum(), rowSums(), etc.
- main data types: int and boolean which starts the numbers in the 2D arrays; boolean gives true or false depending on whether the final answer of the sums are different or not.
- Random
- Used to generate type number greater than or equal to 0.0 and less than 1.0. The default random number always generated between 0 and 1. If you want to specific range of values, you have to multiply the returned value with the magnitude of the range.
- Do nothing by value
- Doesn't change numbers locally
- Change variable's subvalue
- In the function, it keeps the changed value as local
- Int by Reference
- Value of int changes locally
- Menu
- Use of catch, try, and while
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");
}
}
}
}
Exploring 2017 FRQ
- Two data types: int and boolean
- Since the question involves identifying and processing the digits of a non-negative integer, it's best to use int
- Boolean is used to store numbers as true or false if even or odd
- Main methods are Digits and isStrictlyIncreasing
- Digits utilizes if, while statements
- isStrictlyIncreasing utilizes for loops
/// Part A
public Digits(int num)
{
digitList = new ArrayList<Integer>();
if (num == 0){
digitList.add(new Integer(0));
}
while (num > 0)
{
digitList.add(0, new Integer(num % 10));
num /= 10;
}
}
/// Part B
public boolean isStrictlyIncreasing()
{
for (int i = 0; i < digitList.size()-1; i++){
if (digitList.get(i).intValue() >= digitList.get(i+1).intValue())
{
return false;
}
}
return true;
}
/* This is wrapper class...
Objective would be to push more functionality into this Class to enforce consistent definition
*/
public abstract class Generics {
public final String masterType = "Generic";
private String type; // extender should define their data type
// generic enumerated interface
public interface KeyTypes {
String name();
}
protected abstract KeyTypes getKey(); // this method helps force usage of KeyTypes
// getter
public String getMasterType() {
return masterType;
}
// getter
public String getType() {
return type;
}
// setter
public void setType(String type) {
this.type = type;
}
// this method is used to establish key order
public abstract String toString();
// static print method used by extended classes
public static void print(Generics[] objs) {
// print 'Object' properties
System.out.println(objs.getClass() + " " + objs.length);
// print 'Generics' properties
if (objs.length > 0) {
Generics obj = objs[0]; // Look at properties of 1st element
System.out.println(
obj.getMasterType() + ": " +
obj.getType() +
" listed by " +
obj.getKey());
}
// print "Generics: Objects'
for(Object o : objs) // observe that type is Opaque
System.out.println(o);
System.out.println();
}
}
public class People extends Generics {
// Class data
public static KeyTypes key = KeyType.title; // static initializer
public static void setOrder(KeyTypes key) {Cupcake.key = key;}
public enum KeyType implements KeyTypes {name, email, grade, age}
// Instance data
private final String email;
private final int grade;
private final String age;
// Constructor
People (String email, int grade, String age)
{
this.setType("Name");
this.frosting = frosting;
this.sprinkles = sprinkles;
this.flavor = flavor;
}
/* 'Generics' requires getKey to help enforce KeyTypes usage */
@Override
protected KeyTypes getKey() { return Cupcake.key; }
/* 'Generics' requires toString override
* toString provides data based off of Static Key setting
*/
@Override
public String toString() {
String output="";
if (KeyType.flavor.equals(this.getKey())) {
output += this.flavor;
} else if (KeyType.frosting.equals(this.getKey())) {
output += this.frosting;
} else if (KeyType.sprinkles.equals(this.getKey())) {
output += "00" + this.sprinkles;
output = output.substring(output.length() - 2);
} else {
output = super.getType() + ": " + this.flavor + ", " + this.frosting + ", " + this.sprinkles;
}
return output;
}
// Test data initializer
public static Cupcake[] cupcakes() {
return new Cupcake[]{
new Cupcake("Red", 4, "Red Velvet"),
new Cupcake("Orange", 5, "Orange"),
new Cupcake("Yellow", 6, "Lemon"),
new Cupcake("Green", 7, "Apple"),
new Cupcake("Blue", 8, "Blueberry"),
new Cupcake("Purple", 9, "Blackberry"),
new Cupcake("Pink", 10, "Strawberry"),
new Cupcake("Tan", 11, "Vanilla"),
new Cupcake("Brown", 12, "Chocolate"),
};
}
public static void main(String[] args)
{
// Inheritance Hierarchy
Cupcake[] objs = cupcakes();
// print with title
Cupcake.setOrder(KeyType.title);
Cupcake.print(objs);
// print flavor only
Cupcake.setOrder(KeyType.flavor);
Cupcake.print(objs);
}
}
Cupcake.main(null);