Data Types
static String add(int a1, int b1) {
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int total = number0 + number1;
String finalvalue = Integer.toBinaryString(total);
return finalvalue;
}
System.out.println(add(1,1));
System.out.println(add(0,1));
System.out.println(add(1,10));
System.out.println(add(1,110));
Start with some small code excercises
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. Expression of these in Class or PBL forms is an option. But the review must be easy for me to see work.
// int
System.out.println("integer:");
int[] intArray = new int[5];
int sum = 0;
for (int i = 0; i < intArray.length; i++) {
intArray[i] = (int) (Math.floor(Math.random() * 100));
System.out.println(i + ": " + intArray[i]);
sum += intArray[i];
}
System.out.println("Sum: " + sum);
// Wrapper Class
ArrayList<Integer> intArrayList = new ArrayList<>();
for (int i : intArray){
intArrayList.add(new Integer(i));
}
public class doubleArray {
public static void main(String[] args) {
// declare an array of doubles
double[] dubarray = {1.1, 2.2, 3.34, 5.56};
// print out the values of the array
for (int i = 0; i < dubarray.length; i++) {
System.out.println("Value " + i + " = " + dubarray[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.
}
}
}
doubleArray.main(null);
public class isatortoise {
public static void main(String[] args) {
boolean tortoise = true;
if(tortoise == true){
System.out.println("Shellby is a tortoise");
}
else{
System.out.println("Shellby is an aquatic turtle");
}
}
}
isatortoise.main(null);
import java.util.Random;
public class charalphabets {
public static void main(String[] args) {
Random rand = new Random(); // create random object to generate random number
char[] alphabets = {'a', 'b', 'c', 'd', 'e'};
char randomletter = alphabets[rand.nextInt(alphabets.length)]; // next Int method of the rand object generates a random integer that retrieves a random vowel
System.out.println("The random letter is " + randomletter);
}
}
charalphabets.main(null);
What are methods?
- In Java, a method is a block of code that, when called, executes the specified tasks listed in it. Consider a method as a little program that performs operations on data and might or might not return a value. Each technique has a unique name.
What are control structures?
- A block of code known as a control structure allows us to alter the course that those instructions take. Conditional branches, loops, and branching statements are the three types. Java has control structures that can alter the course of execution and manage how instructions are carried out.
What FRQ did you explore?
- 2016 FRQ 1
Diverse Array
- Contains methods and control structures
-
Multiple control structures
- For
- While
- If statements
-
Because it contains arrays, a data type, it falls under the category of data types.
- The majority of code segments, regardless of what they are on, deal with methods and control structures.
Random
- Gives value between 0 and 1
- Double a Math.random value and add 7 to it if you want a random number between 7 and 9.
Do nothing by value
- As a result of changing the subvalue rather than the variable's real value, you are essentially modifying the variable but it does not actually change.
Int by Reference
- Despite the fact that you are acting locally, the int changes its value.
- Essentially states that there is a workaround for the issue that local variable editing is not possible.
Menu
- Use of Try, Catch, and Runnable to regulate program execution
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");
}
}
}
// PART A
public class RandomStringChooser {
private ArrayList<String> words;
public RandomStringChooser(String[] wordArray) {
words = new ArrayList<String>();
for (String w : wordArray)
words.add(w);
}
public String getNext()
{
if (words.size() == 0)
return "NONE";
int i = (int)(Math.random() * words.size());
return words.remove(i);
}
}
// PART B
public RandomLetterChooser(String str) {
super(getSingleLetters(str));
}