Java Data Types
- Sample Binary Addition
- Code Example: Before and After Multiplying by 5
- Converting to Wrapper Class
- Exploring Teacher Code:
import java.util.Scanner;
public class JavaBinaryAdder {
public static void main(String[] args)
{
//Two variables to hold two input binary numbers
long b1, b2;
int i = 0, carry = 0;
//This is to hold the output binary number
int[] sum = new int[10];
//To read the input binary numbers entered by user
Scanner scanner = new Scanner(System.in);
//getting first binary number from user
System.out.print("Enter first binary number: ");
b1 = scanner.nextLong();
System.out.print(b1);
System.out.println();
//getting second binary number from user
System.out.print("Enter second binary number: ");
b2 = scanner.nextLong();
System.out.print(b2);
System.out.println();
//closing scanner after use to avoid memory leak
scanner.close();
while (b1 != 0 || b2 != 0)
{
sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);
carry = (int)((b1 % 10 + b2 % 10 + carry) / 2);
b1 = b1 / 10;
b2 = b2 / 10;
}
if (carry != 0) {
sum[i++] = carry;
}
--i;
System.out.print("Output: ");
while (i >= 0) {
System.out.print(sum[i--]);
}
System.out.print("\n");
}
}
JavaBinaryAdder.main(null);
import java.util.Scanner;
public class MultiplyBy5 {
public static void changeInt(int n) {
System.out.println("In changeInt method");
System.out.println("\tBefore n *= 5: n = " + n); // prints 5
n = n *= 5;
System.out.println("\tAfter n *= 5: n = " + n); // prints 10
}
public static void main(String[] args) {
int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number: ");
n = scanner.nextInt();
System.out.println("Main method before changeInt(n): n = " + n); // prints 5
changeInt(n);
System.out.println("Main method after changeInt(n): n = " + n); // still prints 5
}
}
MultiplyBy5.main(null);
int primitiveInt = n;
Integer[] wrapperIntArray = new Integer[] { primitiveInt };
Integer wrapperInt = wrapperIntArray[0];
Exploring Teacher Code:
What are Methods and Control Structures?
- A method, also known as a function or subroutine, is a block of code that performs a specific task. Methods can be called multiple times and can accept input parameters and return output values. They are used to break down complex tasks into smaller, more manageable units of code.
- Control structures are used to control the flow of execution in a program. They determine the order in which statements are executed based on certain conditions. There are three main types of control structures:
- Conditional statements: These are used to execute a certain block of code only if a particular condition is met. Examples include the "if" statement, the "else" statement, and the "switch" statement.
- 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.
Diverse Arrays
- This code definitely contains multiple Methods and Control Structures. The Methods are seen in functions such as arraySum(), rowSums(), and isDiverse(), as they are called in different places within the class and each do their own procedure. The Control Structures can be seen in the multiple conventional for loops in each of the methods.
- The primary data types in the diverse matrix code are int and boolean as ints are used to stare the numbers within the 2D arrays and a boolean is used to provide the final answer as to whether the sums of the array rows are diverse or not.
Math.random()
-
Math.random()
is a built-in method in Java that returns a pseudo-random double value between 0.0 and 1.0 (inclusive). - This method uses a mathematical algorithm to generate random numbers, which means that the numbers are not truly random but are determined by the algorithm.-
int randomNum = (int)(Math.random() * 10);
returns a value between 0.0 and 1.0, which is then multiplied by 10 and cast to an integer. The resulting value is a random integer between 0 and 9. - If you want to get an integer value between 7 and 9, you can cast the result of the expression to an int, like this:
int randomInt = (int) (Math.random() * 2 + 7);
Here,Math.random() * 2
generates a random value between 0 and 2, and then adding 7 to it will shift the range to be between 7 and 9.
DoNothingByValue
- Seems to be multiple ways in order to change input such as arrays of numbers or strings into default values/empty arrays of 0.
- This is done by creating a default array arr and setting all the values to 0 through the use of conventional for loops. ### IntByReference
- Wraps int inputs into Integers, because they need to be objects in order to work with the swapper method.
- In order to swap values if the latter one is lesser, the value is stored in a tmp variable in order to switch around. ### Menu
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class MultiplyBy5 {
public static void changeInt(int n) {
System.out.println("In changeInt method");
System.out.println("\tBefore n *= 5: n = " + n); // prints 5
n = n *= 5;
System.out.println("\tAfter n *= 5: n = " + n); // prints 10
}
public static void main(String[] args) {
int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number: ");
n = scanner.nextInt();
System.out.println("Main method before changeInt(n): n = " + n); // prints 5
changeInt(n);
System.out.println("Main method after changeInt(n): n = " + n); // still prints 5
System.out.println();
}
}
/**
* 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
// 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("Multiply By 5", () -> MultiplyBy5.main(null)),
new MenuRow("Do Nothing", () -> MultiplyBy5.main(null)),
new MenuRow("Swap if Hi-Low", () -> MultiplyBy5.main(null)),
new MenuRow("Matrix Reverse", () -> MultiplyBy5.main(null)),
new MenuRow("Diverse Array", () -> MultiplyBy5.main(null)),
new MenuRow("Random Squirrels", () -> MultiplyBy5.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();
System.out.println();
// 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")) {
System.out.println("Goodbye!");
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");
}
}
}
}Driver.main(null);
- MenuRow is a method because it's a piece of code grouped together in a way that performs a specific task - initializing each row of the menu - and it's called over and over in the driver class. Though the MenuRow class itself is not a control structure, it is part of a switch case used in the Driver class which is.
- The Driver mainly has a switch case control structure, in which different operations are performed depending on which int is typed into the scanner. For example there is a section of code where there's an if statement stating that if 0 is typed into the scanner, the menu will exited out of.
public static Position findPosition(int num, int[][] intArr) { // input is entered and saved as num
for (int row=0; row < intArr.length; row++) { // iterates through each row
for (int col=0; col < intArr[0].length; col++) { // iterates through each column in the row
if (intArr[row][col] == num) { // if value = num
return new Position(row, col); // return the value
}
}
}
return null;
}
- part b:
public static Position[][] getSuccessorArray(int[][] intArr) {
Position[][] newArr = new Position[intArr.length][intArr[0].length];
for (int row=0; row < intArr.length; row++) {
for (int col=0; col < intArr[0].length; col++) { // iterates through rows and columns
newArr[row][col] = findPosition(intArr[row][col]+1, intArr); // returns the coordinates of where that specific number is in the first array
}
}
return newArr; // displays as a whole new array of coordinates
}