Intro into Arrays

  • An array is a data structure used to implement a collection (list) of primitive or object reference data.

  • An element is a single value in the array

  • The **index** of an element is the position of the element in the array

    • In java, the first element of an array is at index 0.
  • The length of an array is the number of elements in the array.

    • length is a public final data member of an array

      • Since length is public, we can access it in any class!

      • Since length is final we cannot change an array’s length after it has been created

    • In Java, the last element of an array named list is at index list.length -1

A look into list Memory

int [] listOne = new int[5];

This will allocate a space in memory for 5 integers.

ARRAY: [0, 0, 0, 0, 0]
INDEX:  0  1  2  3  4

Using the keyword new uses the default values for the data type. The default values are as follows:

Data Type Default Value
byte (byte) 0
short (short) 0
int 0
double 0.0
boolean false
char ‘\u0000’

What do we do if we want to insert a value into the array?

listOne[0] = 5;

Gives us the following array:

ARRAY: [0, 0, 0, 0, 0]
INDEX:  0  1  2  3  4

What if we want to initialize our own values? We can use an initializer list!

int [] listTwo = {1, 2, 3, 4, 5};

Gives us the following array:

ARRAY: [1, 2, 3, 4, 5]
INDEX:  0  1  2  3  4

If we try to access an index outside of the range of existing indexes, we will get an error. But why? Remember the basis of all programming languages is memory. Because we are trying to access a location in memory that does not exist, java will throw an error (ArrayIndexOutOfBoundsException).

How do we print the array? Directly printing the array will not work, it just prints the value of the array in memory. We need to iterate through the array and print each value individually!

/* lets take a look at the above */

int [] listOne = new int[5]; // Our list looks like [0, 0, 0, 0, 0]

listOne[2] = 33; // Our list looks like [0, 0, 33, 0, 0]
listOne[3] = listOne[2] * 3; // Our list looks like [0, 0, 33, 99, 0]

try {
    listOne[5] = 13; // This will return an error
} catch (Exception e) {
    System.out.println("Error at listOne[5] = 13");
    System.out.println("ArrayIndexOutOfBoundsException: We can't access a memory index that doesn't exist!");
}


System.out.println(listOne); // THIS DOES NOT PRINT THE LIST!! It prints the value in memory
System.out.println(listOne[4]); // This will actually print the vaules in the array
Error at listOne[5] = 13
ArrayIndexOutOfBoundsException: We can't access a memory index that doesn't exist!
[I@1526301
0

Popcorn Hacks!

Write code to print out every element of listOne the following

I did that below. I didn't put it in its own object for simplicity.

/* popcorn hacks go here */
for (int i : listOne) {
    System.out.println(i);
}
/*
 * Alternatively:
 * for (int i = 0; i < listOne.length; i++) {
 *     System.out.println(listOne[i]);
 * }s
 */
0
0
33
99
0

Reference elements

Lists can be made up of elements other than the default data types! We can make lists of objects, or even lists of lists! Lets say I have a class Student and I want to make a list of all students in the class. I can do this by creating a list of Student objects.

Student [] classList;
classList new Student [3];

Keep in mind, however, that the list won’t be generated with any students in it. They are initialized to null by default, and We need to create the students and then add them to the list ourselves.

classList[0] = new Student("Bob", 12, 3.5);
classList[1] = new Student("John", 11, 4.0);
classList[2] = new Student("Steve", 10, 3.75);

Popcorn hacks!

Use a class that you have already created and create a list of objects of that class. Then, iterate through the list and print out each object using: 1) a for loop 2) a while loop

I did this below with a new class I created. I also sued a different method to populate the array than shown above.

/* Popcorn hacks go here */
public class Bird {
    private String species;
    private String color;
    private int weightInGrams;
    private boolean canFly;

    public Bird(String species, String color, int weightInGrams, boolean canFly) {
        this.species = species;
        this.color = color;
        this.weightInGrams = weightInGrams;
        this.canFly = canFly;
    }

    // iteration found here
    public static void main(String[] args) {
        // populating array
        Bird[] birdArray = {new Bird("Crow", "black", 450, true), new Bird("Penguin", "black and white", 1000, false), new Bird("Chicken", "orange", 2585, true)};
        // for loop
        System.out.println("FOR LOOP");
        for (Bird bird : birdArray) {
            System.out.println("Species: " + bird.species);
            System.out.println("\tColor: " + bird.color);
            System.out.println("\tWeight (Grams): " + bird.weightInGrams);
            System.out.println("\tCan it Fly?: " + bird.canFly);
        }
        // while loop
        System.out.println("\nWHILE LOOP");
        int i = 0;
        while (i < birdArray.length) {
            System.out.println("Species: " + birdArray[i].species);
            System.out.println("\tColor: " + birdArray[i].color);
            System.out.println("\tWeight (Grams): " + birdArray[i].weightInGrams);
            System.out.println("\tCan it Fly?: " + birdArray[i].canFly);
            i++;
        }
    }
}

Bird.main(null);
FOR LOOP
Species: Crow
	Color: black
	Weight (Grams): 450
	Can it Fly?: true
Species: Penguin
	Color: black and white
	Weight (Grams): 1000
	Can it Fly?: false
Species: Chicken
	Color: orange
	Weight (Grams): 2585
	Can it Fly?: true

WHILE LOOP
Species: Crow
	Color: black
	Weight (Grams): 450
	Can it Fly?: true
Species: Penguin
	Color: black and white
	Weight (Grams): 1000
	Can it Fly?: false
Species: Chicken
	Color: orange
	Weight (Grams): 2585
	Can it Fly?: true

Enhanced for loops

The enhanced for loop is also called a for-each loop. Unlike a “traditional” indexed for loop with three parts separated by semicolons, there are only two parts to the enhanced for loop header and they are separated by a colon.

The first half of an enhanced for loop signature is the type of name for the variable that is a copy of the value stored in the structure. Next a colon separates the variable section from the data structure being traversed with the loop.

Inside the body of the loop you are able to access the value stored in the variable. A key point to remember is that you are unable to assign into the variable defined in the header (the signature)

You also do not have access to the indices of the array or subscript notation when using the enhanced for loop.

These loops have a structure similar to the one shown below:

for (type declaration : structure )
{
    // statement one;
    // statement two;
    // ...
}

Popcorn Hacks!

Create an array, then use a enhanced for loop to print out each element of the array.

/* Popcorn hacks go here */
int[] arrayShow = {1, 4, 6, 7, 303, 34094, 484, 23094};

for (int i : arrayShow) {System.out.print(i + " ");}
1 4 6 7 303 34094 484 23094 

Min maxing

It is a common task to determine what the largest or smallest value stored is inside an array. in order to do this, we need a method that can ake a parameter of an array of primitive values (int or double) and return the item that is at the appropriate extreme.

Inside the method of a local variable is needed to store the current max of min value that will be compared against all the values in the array. you can assign the current value to be either the opposite extreme or the first item you would be looking at.

You can use either a standard for loop or an enhanced for loop to determine the max or min. Assign the temporary variable a starting value based on what extreme you are searching for.

Inside the for loop, compare the current value against the local variable, if the current value is better, assign it to the temporary variable. When the loop is over, the local variable will contain the approximate value and is still available and within scope and can be returned from the method.

Popcorn Hacks!

Create two lists: one of ints and one of doubles. Use both a standard for loop and an enhanced for loop to find the max and min of each list.

/* Popcorn hacks go here! */
int[] intList = {1, 48, 239, 29, 230, 475, 10, 4, 69};
double[] doubleList = {4.3, 5.67, 23.59, 304.32, 310.3, 49.304};

// using normal for loop
System.out.print("USING STANDARD FOR LOOP: ");
int intMax = intList[0];
int intMin = intList[0];
for (int i = 1; i < intList.length; i++) {
    if (intList[i] > intMax) {intMax = intList[i];}
    if (intList[i] < intMin) {intMin = intList[i];}
}
System.out.print("The maximum of intList is " + intMax + " and the minimum is " + intMin + ". ");
double doubleMax = doubleList[0];
double doubleMin = doubleList[0];
for (int i = 1; i < doubleList.length; i++) {
    if (doubleList[i] > doubleMax) {doubleMax = doubleList[i];}
    if (doubleList[i] < doubleMin) {doubleMin = doubleList[i];}
}
System.out.print("The maximum of doubleList is " + doubleMax + " and the minimum is " + doubleMin + ".");
System.out.println();

// using a for each loop
System.out.print("USING FOR EACH LOOP: ");
int intMax = intList[0];
int intMin = intList[0];
for (int i : intList) {
    if (i > intMax) {intMax = i;}
    if (i < intMin) {intMin = i;}
}
System.out.print("The maximum of intList is " + intMax + " and the minimum is " + intMin + ". ");
double doubleMax = doubleList[0];
double doubleMin = doubleList[0];
for (double d : doubleList) {
    if (d > doubleMax) {doubleMax = d;}
    if (d < doubleMin) {doubleMin = d;}
}
System.out.print("The maximum of doubleList is " + doubleMax + " and the minimum is " + doubleMin + ".");
USING STANDARD FOR LOOP: The maximum of intList is 475 and the minimum is 1. The maximum of doubleList is 310.3 and the minimum is 4.3.
USING FOR EACH LOOP: The maximum of intList is 475 and the minimum is 1. The maximum of doubleList is 310.3 and the minimum is 4.3.

Hacks! (Due 10/22 11:59 PM)

Given an input of N integers, find A, the maximum, B, the minimum, and C the median.

Print the following in this order:

  1. A + B + C
  2. A - B - C
  3. (A + B) * C
import java.util.Arrays;

public class ArrayAnalyzer {
    private int[] integerArray;
    private int N;
    private int A;
    private int B;
    private int C;

    public ArrayAnalyzer() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Input how many integers you want in the array.");
        // HERE'S N
        N = scanner.nextInt();
        integerArray = new int[N];
        for (int i = 0; i < N; i++) {
            int remainingInputs = N - i;
            // string formatting here for fun because haha singularity
            System.out.println("Input " + remainingInputs + " more integer" + (remainingInputs == 1 ? "" : "s") + ".");
            int inputInteger = scanner.nextInt();
            integerArray[i] = inputInteger;
        }
        scanner.close();
        System.out.print("Your array: [");
        for (int i = 0; i < N; i++) {System.out.print(integerArray[i] + ((i == N - 1) ? "]\n" : ", "));}
        System.out.println("Length of Array (N): " + N);
    }

    private void findABC() {
        // sorting array from least to greatest to find info
        int[] sortedArray = integerArray;
        Arrays.sort(sortedArray);
        A = sortedArray[N - 1]; // maximum
        B = sortedArray[0]; // minimum
        // calculating median
        if (N % 2 == 0) { // even number of entries
            C = (sortedArray[N / 2] + sortedArray[(N / 2) - 1]) / 2;
        } else { // odd number of entriess
            C = sortedArray[(N - 1) / 2];
        }
        System.out.println("Maxiumum (A): " + A);
        System.out.println("Minimum (B): " + B);
        System.out.println("Median (C): " + C);
    }

    public static void main(String[] args) {
        ArrayAnalyzer demonstration = new ArrayAnalyzer();
        demonstration.findABC();
    }
}

ArrayAnalyzer.main(null);
Input how many integers you want in the array.


Input 5 more integers.
Input 4 more integers.
Input 3 more integers.
Input 2 more integers.
Input 1 more integer.
Your array: [10, 3, 7, 9, 5]
Length of Array (N): 5
Maxiumum (A): 10
Minimum (B): 3
Median (C): 7

Extra

For extra, I created my own fun program using an array. It gives you a set of five numbers, and you must identify which one is a prime number.

// import to randomly have a prime number at a given index
import java.util.Random;

public class PrimesGame {
    public static boolean isPrime(int number) {
        // positive integers less than 2 are never prime
        if (number < 2) {
            return false;
        }
        for (int i = 2; i * i <= number; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static int[] gameGeneration() {
        int[] intArray = new int[5];
        Random random = new Random();
        int primeIndex = random.nextInt(5);
        for (int i = 0; i < 5; i++) {
            if (i == primeIndex) {
                // Generate a prime number
                do {
                    intArray[i] = random.nextInt(100) + 1;
                } while (!isPrime(intArray[i]));
            } else {
                // Generate a non-prime number
                do {
                    intArray[i] = random.nextInt(100) + 1;
                } while (isPrime(intArray[i]));
            }
        }
        return intArray;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean playing = true;
        System.out.println("Welcome to the Primes Game!");
        while (playing) {
            int[] gameArray = gameGeneration();
            System.out.println("Select the prime number from the numbers below. (Use 1, 2, 3, 4, or 5.)");
            for (int i = 0; i < 5; i++) {
                System.out.println("\t" + (i + 1) + ". " + gameArray[i]);
            }
            int playerChoice = scanner.nextInt();
            scanner.nextLine();
            if (isPrime(gameArray[playerChoice - 1])) {
                System.out.println("Congratulations! You picked the prime number.");
            } else {
                System.out.println("Oh no! That wasn't the prime number.");
            }

            System.out.println("Would you like to play again? (y or n)\n");
            String playAgain = scanner.nextLine();

            if (!(playAgain.equals("y"))) {
                System.out.println("Thanks for playing!");
                playing = false;
            }
        }

        scanner.close();
    }
}

PrimesGame.main(null);
Welcome to the Primes Game!
Select the prime number from the numbers below. (Use 1, 2, 3, 4, or 5.)
	1. 63
	2. 92
	3. 64
	4. 11
	5. 36
Congratulations! You picked the prime number.
Would you like to play again? (y or n)

Select the prime number from the numbers below. (Use 1, 2, 3, 4, or 5.)
	1. 18
	2. 70
	3. 27
	4. 33
	5. 29
Congratulations! You picked the prime number.
Would you like to play again? (y or n)

Thanks for playing!