Lesson 6 - Array
// HACK 1
int[] arrayOne = {1, 3, 5, 7, 9};
for (int num : arrayOne) {
if (num % 2 == 0) {
System.out.println(num);
}
}
// HACK 2
// Answer is B
// HACK 3
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);
// HACK 4
// ANSWER IS B
// HACK 5
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!
}
}
}
// HACK 6
// ANSWER IS D
// HACK 7
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)
// HACK 8
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);
// HACK 9
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);
// FRQ PART A
public void addMembers(String[] names, int gradYear) {
for (String name : names) {
MemberInfo member = new MemberInfo(name, gradYear, true);
memberList.add(member);
}
}