CSC-117 Computer Programming II
Chapter 13 - ARRAYS
This is one of the more important chapters in the book, so study it carefully!

An array is a collection of data items. All data items in the array are of the same type. They are either all integers, all reals, all strings etc. An array is a perfect place to keep lots of data that is of the same type. Let’s look at an example. If you had to write a program that had to contain the grades (percent grades) of three students, you may have added something like this to your program

int grade1;
int grade2;
int grade3;
And if you had to find out which was the largest, you may have written something like this:
large = grade1;
if( grade2 > large ) large=grade2;
if( grade3 > large ) large=grade3;
But now suppose you had to write a program to contain the grades of 30 students, or 100 students, or perhaps the whole college which would be over 1000 students! This would require several thousands of lines of code like the above lines. So we need a better way and the array is the way!

An array is like having several containers or boxes to put our data in. In our above example, our array may be called grades and this array could hold, say, 100 integers, one integer per box. The question is how do you reference these pieces of data? Well, you reference them by referring to an index, which is basically the box number. If we had an array of 6 grades they might look like this:

data:     24     78     54     12     21     35

index:     0      1       2       3       4       5

If we wanted to reference the box that had the 21 in it we could write something like this:
someGrade = grades[4];
Notice the square brackets! That is what you use to reference an array element or box. Also notice that the array indices (indexes) DO NOT START AT 1. THEY START AT 0! This is just a quirk of Java and other programming languages such as C or C++. Just remember that the first element of the array is in box 0, not box 1.

There are several things we would like to do with an array. Here are some:

  • create an array (including specifying how many boxes are in it)
  • put some values in an array
  • display the contents or the entire array or a part of it
  • search the array to see if some value is in it or not
  • add up the contents (for example, maybe we need to find the average of a bunch of numbers


Creating an array
 

To create an array you need to tell Java two things: 1) that you wish to create an array and 2) how many items (boxes) are going to be in it.

To tell Java you want an array you must write something like this:

int[] grades;
String[] names;
float[] heights;
To tell Java how many elements are in the array you need to write something like this:
grades = new int[ 30 ];
names = new String [ 100];
heights = new float [ 50];
You can combine these by typing:
int[] grades = new int[ 30 ];
Indices
 
In order to get a piece of data into the array, you should reference the array position where you wish to put the data by the array index. For example:
grades [ 2 ] = 54;
or
names [ 99 ] = "Richard";
(Here names[99] is the last element of the array. Why?)

You can also put stuff in the array from textfields, like

grades [ 2 ] = Integer.parseInt(inputField.getText( ));
names[99] = someField.getText( ));
You can print array elements like this:
g.drawString(" Your grade is " + grades[3], 10, 10);
g.drawString(" Hi. My name is " + names[99], 60, 60);
We are still a long way off from what we want to do though. Let’s look back at our original grades array. It has 6 elements. We may have to get it working like this:

To create it:

int[] grades = new int[6];
To initialize it:
grades[0] = 34;
grades[1] = 78;
grades[2] = 54;
grades[3] = 12;
grades[4] = 21;
grades[5] = 35;
To add them all up:
sum = grades[0]+grades[1]+grades[2]+grades[3]+grades[4]+grades[5];

It doesn’t look like we’ve gained much, YET!

Here’s a trick for initializing the contents of an array, if you know what is to go into it. Instead of creating it they way we did above, we can write:

int [] grades = { 34, 78, 54, 12, 21, 35 };
Instead of summing them they way we did above, since the index into an array can be a number between 0 and 5 (in our example) , we can use a for loop like this:
sum = 0;
for ( int index = 0; index < 6; index++)
    sum = sum + grades[ index ];
Now this may not seem like much difference, but consider what you would have to do if the array contained 1000 elements. I don’t think you want to write that long summation. The for loop is a lot easier to write. Just change the 6 to 1000.
The length of an array
In fact you do not even have to hardcode the 1000 into the for loop as was suggested above. You can always refer to the length of an array (the number of elements in it) like this:
grades.length
Then our for loop would become
sum = 0;
for ( int index = 0; index < grades.length; index++)
    sum = sum + grades[ index ];


Passing arrays as parameters

Sometimes you need to pass an array as a parameter to a method. Suppose we had three arrays;
 
float[] height = new float[100];
float[] width = new float [200];
float[] gpa = new float[1000];
(Notice that these arrays are all different sizes.)

Suppose also that we wanted to try to create a general method that would return the average of all of the numbers in an array. We would like it to work no matter which of the above three arrays we would send it. Here is how you would write the method.

public float average( float[] someArray) {
    float sum = 0.0f;
    for ( int index = 0; index < someArray.length; index++)
        sum = sum + someArray[index];
    average = sum/someArray.length;
    return average;
}
Study this carefully. It works and it’s kind of neat! We can find the averages for our three arrays very quickly now by writing:
avgHeight = average(height);
avgWidth = average(width);
avgGpa = average(gpa);
We just send the same of the array off as a parameter to the average method and it does the rest!


A Sample Program

Now it’s time to put all of this together and look at an example program. The screen applet will look like Figure 13.1 in your text:

Here is the program:
 

// Sample program
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

//Define the Applet. Note: We have a MouseListener now
public class Rainfall extends Applet
                    implements AdjustmentListener, MouseListener {

//Define data. Note: The rainfall data is kept in a separate Table class
private Table rainData;
private TextField value;

//Initialize the basic items of the screen
public void init( ) {

rainData = new Table ( );
Label lab = new Label("Enter number and click component");
add(lab);
value = new TextField(10);
add(value);
value.addActionListener(this);
this.addMouseListener(this);
}

//Display data. Note: This is all done within the Table class
public void paint( Graphics g ) {
        rainData.display(g);
}

//Take action if a number was entered
public void actionPerformed( ActionEvent event){

int newValue = Integer.parseInt( value.getText( ));
//Call a method to store the value somewhere in the Table class
rainData.setValue(newValue);
repaint( );
}

//If someone clicks the mouse on the screen, find out where
public void mouseClicked( MouseEvent event) {

int yCoord = event.getY( ):
//Determine which array element was clicked
rainData.selectComponent(yCoord);
repaint( );
}

// Define other mouse events to implement the MouseListener
// even though we will not use them for this program
public void mouseReleased(MouseEvent event){}
public void mousePressed(MouseEvent event){}
public void mouseEntered(MouseEvent event) {}
public void mouseExited (MouseEvent event) {}

}// End of Applet program

//Now define the Table class and all of the array processing
class Table {

//Data for array
private final int tableSize = 7;
private int[] rain = new int[tableSize];
private int index;
private int newValue;
private int sum = 0;

//Data for graphics
private final int startX = 20;
private final int startY = 60;
private final int boxHeight = 20;
private final int boxWidth = 60;

//Define the method to display data
public void display( Graphics g ) {

int y = startY;
for ( int s = 0 ; s < rain.length ; s++ ) {
    //Draw a box
    g.drawRect(startX, y, boxWidth, boxHeight);
    //Put number in box
    g.drawString(Integer.toString( rain[s] ),
                        startX, y + boxHeight*3/4;
    //Go to next box and number
    y = y + boxHeight;
}

//Add the rainfall data
addValues( ){

// Print out the sum
g.drawString(" Total rainfall is " + sum, 100, 100);
}

//Store the value from the text field until user selects an array box
public void setValue( int value){
        newValue = value;
}

//Determine which box was clicked and store array element
public void selectComponent ( int y ) {

index = ( y - startY) / boxHeight;
rain [ index ] = newValue;
}

// Add the values in the array. Note: this is a private method - why?
private void addValues ( ) {

sum = 0;
for ( int s = 0 ; s < rain.length ; s++ )
        sum = sum + rain[s];
}

// This is the end of the Table class and complete program

}


We’ll talk about all of this in class and try to get it to work.

- from Java for Students, by Bell and Parr