Unit 6 Arrays
Learnings and application to FRQ
- 6.1 Array Creation and Access
- 6.2 Traversing Arrays
- 6.3 Enhanced For Loops
- 6.4 Developing Algorithms using Arrays
- Hack 1
- Hack 2
- Hack 3
- Hack 4
- Hack 5
- Hack 6
- Hack 7
- Hack 8
- Hack 9
- FRQ Part A
6.1 Array Creation and Access
- Used to store one data type
- Fixed size and canno tbe chnaged
- Import array through: import java.util.Arrays;
- Making Arrays: using constructors or using pre-initialized arrays
6.2 Traversing Arrays
- For loop or while loop
- Bound errors: appears when using loops to access array elements
- When there's not enough items to reach an index
6.3 Enhanced For Loops
- Traverse through most data structures
- Elements in array need to have something done to
- Mutator methods: set the value on instance variables
6.4 Developing Algorithms using Arrays
- Minimum and maximum of a list of elements
- Compute sum, average, or mode
- If you want to find if an array has a specific property
- Can determine duplicates
- .length can be used to find the length of an array
- array [i] to find the value
- change value: array [i] = new element
for (int num : arrayOne) {
if (num % 2 == 0) {
System.out.println(num);
}
}
import java.util.Arrays;
public class arraySorter {
public static void main(int[] a) {
Arrays.sort(a);
for (int i : a) {
System.out.println(i);
}
}
}
int[] myNumbers = new int[] {5, 3, 4, 1, 2};
arraySorter.main(myNumbers);
public class ForEachDemo
{
public static void main(String[] args)
{
int[] highScores = { 10, 9, 8, 8};
String[] names = {"Jamal", "Emily", "Destiny", "Mateo"};
// for each loop with an int array
for (int value : highScores)
{
System.out.println( value );
}
// for each loop with a String array
for (String value : names)
{
System.out.println(value); // this time it's a name!
}
}
}
public class leftShifted {
public static int[] main(int[] a) {
int first = a[0];
for (int i=1; i<a.length; i++) {
a[i-1] = a[i];
}
a[a.length-1] = first;
return a;
}
}
int[] array = {7,9,4};
int[] array_out = leftShifted.main(array);
Arrays.toString(array_out)
public class findDuplicate {
public static int main(int[] a, int b) {
int d=0;
for (int number : a) {
if (number==b) {
d++;
}
}
return d;
}
}
int[] array = {7,7,9,4};
findDuplicate.main(array, 7);
public class reverseString {
public static char[] main(char[] s) {
char[] reverse = new char[s.length];
for (int i=s.length-1; i>=0; i--) {
reverse[s.length-i-1] = s[i];
}
return reverse;
}
}
String s = "hello";
char[] c = s.toCharArray();
char[] reverse = reverseString.main(c);
// Arrays.toString(reverse)
String reversed = new String(reverse);
System.out.println(reversed);
public void addMembers(String[] names, int gradYear) {
for (String name : names) {
MemberInfo member = new MemberInfo(name, gradYear, true);
memberList.add(member);
}
}