Units 6-10 HW and Vocab
Units 6-10 HW and Vocab.
public class ArrayMethods {
private static int[] values = {1, 2, 3, 4, 5};
public void printElements(){
for(int a = 0; a < values.length; a++){
System.out.println(values[a]);
}
}
public void swapElements(){
int firstElement = values[0];
values[0] = values[values.length-1];
values[values.length-1] = firstElement;
}
public void changeToZero() {
for(int a = 0; a < values.length; a++){
if(values[a] % 2 == 0){
values[a] = 0;
}
}
}
public static boolean checkSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println("First and Last Element Swap: ");
ArrayMethods swapElements = new ArrayMethods();
swapElements.swapElements();
swapElements.printElements();
System.out.println("Replacing All Elements w/ Zero: ");
ArrayMethods changeToZero = new ArrayMethods();
changeToZero.changeToZero();
changeToZero.printElements();
System.out.println("Array In Increasing Order: " + (checkSort(values)));
}
}
ArrayMethods.main(null);
Vocab
- Arrays are simply ordinary primitives/non-primitives but in a list format. If you have a string they would be separated by commas. For example "Dog, Cat, Bear, Owl" Integer are like this as well except without quotations.
- An array declaration is when you first initialize the array. An example of this is seen above with: "private static int[] values = {1, 2, 3, 4, 5};"
- The array index are the elements of the array in a numbered list starting from 0. Like in the example used above there would be an index up to 4.
ArrayList<Integer> n = new ArrayList<Integer>();
boolean a;
boolean b;
for (int i = 0; i < 5; i++){
n.add(i);
}
for (int i = 5; i > 0; i--){
n.add(i);
}
System.out.println("HashCode: " + n.hashCode());
System.out.println("Original: " + n);
n.sort(Comparator.reverseOrder());
System.out.println("Sorted: " + n);
System.out.println("HashCode: " + n.hashCode());
Collections.swap(n, 4, 0);
System.out.println("Swapped first and last: " + n);
System.out.println("HashCode: " + n.hashCode());
for (int i=0; i < n.size() - 1; i++){
if (!(n.get(i) <= n.get(i + 1))){
boolean a = false;
}
if (!(n.get(i) >= n.get(i + 1))){
boolean b = false;
}
}
if (a){
System.out.println("ascending");
}
if (b){
System.out.println("descending");
}
else{
System.out.println("neither");
}
Vocab
- Array lists are (as the name implies) a list of arrays. This list can add indexes, remove, clear and many other things. I personally find these extremely helpful in most of my projects.
- Auto boxing is where you convert a primitive type to a wrapper class type. For example when you add a number it gets converted to an integer.
- ArrayList declaration is the initialization for the array list. For example in the code above when I use: "ArrayList
n = new ArrayList ();" It's unlike the OG array because you add the elements after instead of with the declaration.</li> </ul> </div> </div> </div> import java.util.*; import java.lang.Math.*; public class Learning { private int[][] arr = new int[3][3]; private int[][] reversed_arr = new int[3][3]; public static void main(String[] args) { Learning l = new Learning(); l.origInit(); l.reversedArray(); System.out.println("Value of 1,1: " + l.valueOf(1, 1)); System.out.println("Sum of products of rows: " + l.productSum()); Learning w = new Learning(); w.origInit(); w.reversedArray(); System.out.println("Value of 2,1: " + w.valueOf(2, 1)); System.out.println("Sum of products of rows: " + w.productSum()); } public void origInit() { System.out.println("\nOriginal array:"); // Assign a random value to the 2D array and print it for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { // Assign a random value to the 2D array using math.random() arr[i][j] = (int) (Math.random() * 10); System.out.print(arr[i][j] + " "); } System.out.println(); } } public void reversedArray() { System.out.println("\nReversed array:"); // Reverse the 2D array and print it for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { // Reverses array by going backwards through the original array reversed_arr[i][j] = arr[arr.length - 1 - i][arr[i].length - 1 - j]; System.out.print(reversed_arr[i][j] + " "); } System.out.println(); } } public int productSum() { int product = 1; int sum = 0; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { // multiply product by value at this array index product *= arr[i][j]; } // add product to sum after all in row were multiplied, then reset product back to 1 sum += product; product = 1; } return sum; } public int valueOf(int a, int b) { // try to get array value, return exception if can't try { return arr[a][b]; } catch (Exception e) { System.out.println("Error: " + e); return -1; } } } Learning.main(null);
- 2D arrays are made of a type of coordinate system. It's most commonly used to create tables of information just like in this case where we have a product table. It can also be used to create text images like what we did in the first trimester.
- 2D array declaration is how you create the array. For example in the code I used above it says, "private int[][] arr = new int[3][3];"
- Rows are the values along the X-axis.
- Columns are the values along the y-axis.
public class WorldCup { public String team1; public String team2; public String color; public WorldCup (String team1, String team2, String color){ this.team1 = team1; this.team2 = team2; this.color = color; } public String getTeam1(){ return team1; } public String getTeam2(){ return team2; } public void main(String[] args) { System.out.println("Team 1: " + this.team1); System.out.println("Team 2: " + this.team2); System.out.println("Team Colors: " + this.color); } } public class Argentina extends WorldCup { public Argentina(String team1, String team2, String color){ super(team1, team2, color); } } public class Portugal extends WorldCup { public Portugal(String team1, String team2, String color){ super(team1, team2, color); } } Argentina arg = new Argentina("Argentina", "Null", "Blue and White"); Portugal por = new Portugal("Portugal", "Null", "Green and Red"); arg.main(null); por.main(null);
import java.time.LocalDate; import java.time.Period; import java.time.ZoneId; import java.util.Date; public class Person { private String name; private String birthday; private int age; public Person (String name, String birthday){ this.name = name; this.birthday = birthday; } // getters public String getName(){ return name; } public String getBirthday(){ return birthday; } // calculate age public int getAge(){ LocalDate date = LocalDate.parse(this.birthday); return Period.between(date, LocalDate.now()).getYears(); } // to String for general person public String toString(){ return("Name: " + this.getName() + ", Birthday: " + this.getBirthday() + ", Age: " + this.getAge()); } } public class Student extends Person { private int grade; private double gpa; private String favSubject; public Student (String name, String birthday, int grade, double gpa, String favSubject) { super(name, birthday); this.grade = grade; this.gpa = gpa; this.favSubject = favSubject; } // additional getters for attributes specific to subclass public int getGrade(){ return grade; } public double getGPA(){ return gpa; } public String getFavSubject(){ return favSubject; } @Override // custom toString() for Student subclass public String toString(){ return("Name: " + this.getName() + ", Birthday: " + this.getBirthday() + ", Age: " + this.getAge() + ", Grade: " + this.getGrade() + ", GPA: " + this.getGPA() + ", Favorite Subject: " + this.getFavSubject()); } } public class Teacher extends Person { private int yrsExperience; private String hmtwn; private String subTaught; public Teacher(String name, String birthday, int yrsExperience, String hmtwn, String subTaught){ super(name, birthday); this.yrsExperience = yrsExperience; this.hmtwn = hmtwn; this.subTaught = subTaught; } public int getYrsExperience(){ return yrsExperience; } public String getHmtwn(){ return hmtwn; } public String getSubTaught(){ return subTaught; } @Override public String toString(){ return("Name: " + this.getName() + ", Birthday: " + this.getBirthday() + ", Age: " + this.getAge() + ", Years of Experience: " + this.getYrsExperience() + ", Hometown: " + this.getHmtwn() + ", Subject Taught: " + this.getSubTaught()); } } public class Homework{ public static void main(String[] args) { Person p = new Person("Bob", "2018-05-05"); System.out.println("Person: " + p); Student s = new Student("Joe", "2010-11-01", 11, 4.9, "Math"); System.out.println("Student: " + s); Teacher t = new Teacher("Mr. Blob", "1652-11-09", 300, "San Diego", "AP Bio"); System.out.println("Teacher: " + t); // inheritance hierarchy, reference type and object type are not the same Person p2 = new Teacher("Mr. Mort", "1990-12-10", 11, "San Diego", "Computer Science"); System.out.println("Teacher: " + p2); } } Homework.main(null);
- Inheritance is simply a parent-child class system. The child inherits the parents attributes but the child can also build on its own attributes. The child can also have children of its own for a complex inheritance system. Looking at the example above we can see how the parent class "Team" passes all its traits down to the child class of Argentina, Portugal, France, and US. The attributes state the name, country, wins, and loses.
- To put it out of metaphorical terms it's superclasses and subclasses.
- Override is when the subclass had the same method signature as the superclass.
- Polymorphism is where you can use the same method across multiple objects and is essentially one of the most important concepts of coding.
// Recursion public class fibo{ public static int fibonacciRecursion(int x){ if(x == 0){ return 0; } if(x == 1 || x == 2){ return 1; } return fibonacciRecursion(x-2) + fibonacciRecursion(x-1); } public static void main(String args[]) { int n = 25; System.out.print(n + " numbers in sequence:\n"); for(int i = 0; i < n; i++){ System.out.print(fibonacciRecursion(i) + " "); } } } fibo.main(null)
- Recursion is where a function calls to itself in order to loop until a condition is met. This is usually in the form of an if-else statement where if its else then it just loops again with a different input. Refer to the example above.
- Iteration is where you describe code that is to be looped. For example is recursion the code that's being looped is a function that keeps calling to itself.
- Base case is where a solution is too simple and it doesn't even need to use recursion. In this example above it's the check for if X is equal to 0, 1 or 2.
- Recursive case the else part of the function. When it's not the base case it runs the recursive case.