Session 12: Array examples

Simple tasks (Sections 5.3 and 5.4)
    Finding an array element
Finding the mode
Arrays holding records (Section 5.6)
    The class PhoneBookEntry
    The class PhoneBook
    The class PhoneBookQueries

Simple tasks

Textbook: Sections 5.3 and 5.4

Finding an array element

The most common thing you'll want to do to an array is to walk through the array doing something. I want to look at one particular thing you might want to do to an array: find a particular element within the array.

To do this, we might go through the array looking for possible matches. When we find a match, we stop.

int i;
for(i = 0; i < arr.length; i++) {
    if(arr[i] == value) break;
}
if(i == arr.length) {
    IO.print(value + " not found in array");
} else {
    IO.print(value + " found at array index " + i);
}
Notice that in this case it was important that we define i outside the for loop, since we wanted to use its final value after the for loop also.

Finding the mode

You won't always want to go through the array step by step. Sometimes you'll go through the array more or less randomly.

Consider, for example, the following program to find the most commonly occurring test score. To do this, we'll maintain an array saying how many times each test score has occurred.

public class FindMode {
    public static void main(String[] args) {
        int[] tally = new int[101];
        for(int i = 0; i < tally.length; i++) tally[i] = 0;

        IO.print("How many students? ");
        int num = IO.readInt();
        IO.println("Type 'em.");
        for(int i = 0; i < num; i++) tally[IO.readInt()]++;

        int max_i = 0;
        for(int i = 1; i < num; i++) {
            if(tally[i] > tally[max_i]) max_i = i;
        }
        IO.print("Mode is " + max_i);
    }
}
The first and third for loops here are doing using the sequential access we've seen so far. The middle one jumps all over the tally array, based on which score it is currently reading.

Arrays holding records

Textbook: Section 5.6

Now let's do an extended example. Say we want to program an electronic phone book. We want to allow the user to read entries, to search entries, and to remove entries.

Our design will break this into three pieces, which will correspond to our classes: A phone book entry object, a phone book object, and a class for interfacing with the user.

The class PhoneBookEntry

For a single phone book entry, there are just two items to remember: A name and a number. Since the entry doesn't change, this will be an immutable type. The only thing people will ever want to do on a phone book entry is access the data, so we'll just write two methods: getName() and getNumber().

import csbsju.cs160.*;

public class PhoneBookEntry {
    private String name;
    private String number;

    public PhoneBookEntry(String nam, String num) {
        name = nam;
        number = num;
    }
    public String getName() { return name; }
    public String getNumber() { return number; }
}

The class PhoneBook

A phone book is basically an array of phone book entries. In fact, the two fields of the phone book object are the array of entries (called entries, and a count of the number of entries it contains (num_entries).

There are three basic methods that we want to execute: We might want to add a new entry, we might want to find an entry, or we might want to remove an entry. Additionally, I'll add a method isFull() that indicates whether the phone book is full yet.

import csbsju.cs160.*;

public class PhoneBook {
    public static final int MAX_ENTRIES = 100;

    private PhoneBookEntry[] entries;
    private int num_entries;

    public PhoneBook() {
        entries = new PhoneBookEntry[MAX_ENTRIES];
        num_entries = 0;
    }
    public boolean isFull() {
        return num_entries == MAX_ENTRIES;
    }
    public void add(PhoneBookEntry entry) {
        // We check to make sure there's room and that the
        // entry isn't null, just to make sure.
        if(entry != null && num_entries < MAX_ENTRIES) {
            // We add the entry at the end of the entries we have.
            entries[num_entries] = entry;
            ++num_entries;
        }
    }
    public PhoneBookEntry find(String name) {
        // We search through the entries we have for the name.
        for(int i = 0; i < num_entries; i++) {
            if(entries[i].getName().equals(name)) return entries[i];
        }
        return null;
    }
    public PhoneBookEntry delete(String name) {
        // We search through the entries we have for the name.
        for(int i = 0; i < num_entries; i++) {
            if(entries[i].getName().equals(name)) {
                // When we find it, we'll move the last entry into
                // the current slot, replacing the found one.
                PhoneBookEntry ret = entries[i];
                entries[i] = entries[num_entries - 1];
                --num_entries;
                return ret;
            }
        }
        return null;
    }
}

The class PhoneBookQueries

The final class is just for handling the user interface, working with the PhoneBook class. It has a second method, to handle the non-quit operations.

import csbsju.cs160.*;

public class PhoneBookQueries {
    public static void main(String[] args) {
        PhoneBook book = new PhoneBook();

        while(true) {
            IO.print("Operation (a/f/d/q)? ");
            String op = IO.readLine();
            if(op.equals("q")) break;

            handleOperation(book, op);
        }
        IO.println("Good-bye");
    }
    public static void handleOperation(PhoneBook book, String op) {
        if(op.equals("a")) {
            if(book.isFull()) {
                IO.println("Directory currently full");
            } else {
                IO.print("Name? ");
                String name = IO.readLine();
                IO.print("Number? ");
                String num = IO.readLine();
                book.add(new PhoneBookEntry(name, num));
            }
        } else if(op.equals("f")) {
            IO.print("Name? ");
            String name = IO.readLine();
            PhoneBookEntry entry = book.find(name);
            if(entry == null) {
                IO.println("I couldn't find " + name + ".");
            } else {
                IO.println("Number: " + entry.getNumber());
            }
        } else if(op.equals("d")) {
            IO.print("Name? ");
            String name = IO.readLine();
            PhoneBookEntry entry = book.delete(name);
            if(entry == null) {
                IO.println("I couldn't find " + name + ".");
            } else {
                IO.println(name + " deleted.");
            }
        } else {
            IO.println("Unrecognized operation: `" + op + "'");
        }
    }
}