Array Examples

Searching For an Int in and Array of Ints

Consider the following block of code:

int[] array = new int[5];            // All elements initially 0
array[0] = 1;
array[1] = 3;
array[2] = 5;

boolean found = search(array, 3);    // found is true
found = search(array, 2);            // found is false
found = search(array, 0);            // found is true

Write a method named search that has two parameters.  The first parameter is a reference to an array of integers and the second parameter is an integer.  The method returns true if the value of the second argument is an element in the array referenced by the first.  Otherwise it returns false.

private static boolean search(int[] array, int num) {
    boolean found = false;
    for(int i = 0; i < array.length; i++) {
        if (array[i] == num) {
            found = true;
            break;
        }
    }
    return found;
}

Adding Unique Elements to an Array Using Search

Write a block of code that repeatedly asks the user to enter an integer until the user has entered 5 different numbers.

Scanner sc = new Scanner(System.in);
int[] array = new int[5];
int numElements = 0;

while (numElements < 5) {
    System.out.println("Please enter an integer:");
    int num = sc.nextInt();
    boolean found = search(array, num);
    if (!found) {
        array[numElements] = num;
        numElements++;
    }
}

Searching For a String in an Array of Strings

Consider this code:

String[] array = new String[5];
array[0] = "One";
array[1] = "Two";
array[2] = "Tee";

boolean found = search(array, "Tee");   // found is true
found = search(array, "Red");           // found is false
found = search(array, null);            // found is false

Write a method named search that has two parameters.  The first parameter is a reference to an array of Strings and the second parameter is a reference to a non-null String.  The method returns true if the String referenced by the second parameter is in the array referenced by the first parameter. Otherwise it returns false.

boolean search(String[] array, String word) {
    for(int i = 0; i < array.length; i++) {
        if (array[i] == null) {
            return false;
        }
        if (array[i].equals(word)) {
            return true;
        }
    }
    return false;
}

Varargs – Variable Length Arguments

When we define a function we may want to allow the user to pass an arbitrary number of arguments into the function.  We can do this with varargs.  A vararg (variable-length argument) is specified with three periods (…) between the type and variable name in the function’s parameter list as shown below.

static void printNames(String ... names) {
    ...
}

This syntax tells the compiler that printNames can be called with zero or more String arguments.  Internally, names is declared as an array of type String that we can access as normal.

static void printNames(String ... names) {
    for (String name : names) {
        System.out.println("Name: " + name);
    }
}

A function can also have other parameters in addition to a variable length argument, however the variable length argument must be the last parameter listed.

static void printNames(String greeting, String ... names) {
    for (String name: names) {
        System.out.println(greeting + " " + name);
    }
}

 

Restriction:  There can be only one variable length argument.

2D Arrays

We can declare 2-dimensional arrays as follows.

int[][] m1 = new int[3][3];

Here m1 has 3 rows, each of length 3.  You can also declare a multi-dimensional array with rows of a length different than the number of columns.  Below m2 has 2 rows, each of length 3.

int[][] m2 = new int[2][3];

2D arrays are just arrays of arrays. So we can do the following.

m2[0] = new int[3];
m2[1] = new int[3];

You can also initialize a multi-dimensional array when it is declared.  Here is a 2D array whose rows are of different lengths.

int[][] matrix = {
    {1, 0, 0},
    {0, 1},
    {1}
};

Iterating Over a 2D Array

We can iterate over the elements of a 2D array using nested for-loops.  If we don’t need to modify the values stored in the matrix, since 2D arrays are just arrays of arrays we can use for-each loops as shown below.

for (int[] arr:  matrix) {
    for (int elm : arr) {
        System.out.printf("%d ", elm);
    }
}

If we need to modify the values stored in the matrix we can use a regular for-loop and iterate over the indices of the matrix.

for(int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        if (i == j) {
            matrix[i][j] = 1;
        }
    }
}

Catching Exceptions

Consider the following code:

import java.util.Scanner;

public class Driver {
    public static void main(String[] args) {
        int[] list = {2, 4, 6};
        Scanner sc = new Scanner(System.in);
        int index = 0;

        while(index != -1) {
            System.out.println("Pick a number (or -1 to stop)");
            index = sc.nextInt();
            System.out.println(list[index]);
        }
    }
}

When run, if the user enters 3, an ArrayIndexOutOfBoundsException will be thrown causing the program to terminate.

Exceptions

Per our textbook (pp. 213), “An exception is an abnormal condition that arises in a code sequence at run time.  In other words, an exception is a run-time error.”

A Java Exception is an object that is created dynamically at runtime when some exceptional (not necessarily erroneous) condition occurs.  An Exception object can be thought of as a message that can be thrown (to avoid handling the exceptional condition) or caught (to handle the exceptional condition).

The Fix

To fix the original example we can simply put the code that accesses the array in a try-catch block and catch the Exception that occurs and handle it.

import java.util.Scanner;

public class Exceptions {
    public static void main(String[] args) {
        int[] list = {2, 6, 8, 1, 4, 9, 2, 5};
        Scanner sc = new Scanner(System.in);
        int index = 0;

        while(index != -1) {
            System.out.println("Pick a number (or -1 to stop)");
            index = sc.nextInt();

            try {
                System.out.println(list[index]);
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("Number out of bounds");  //continue
            }
        }
    }
}

We’ll cover exceptions in depth in CSCI-200.  What you have here should allow us to proceed and discuss reading and writing files.