Unit 6 Work
Unit 6 CB
Arrays have a fixed size, while Arraylists do not.
Can make arrays pre-initialized or with constructors.
ArrayIndexOutOfBoundsException thrown can happen when using loops to access array elements
int[] arrayOne = {1, 3, 5, 7, 9};
for (int num : arrayOne) {
if (num % 2 == 0) {
System.out.println(num);
}
}
// B
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);
// B
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!
}
}
}
// D
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);
}
}