Chapter 9: Arrays

Suppose I want to store 4 numbers input by the user and then add them up. Given what we know now, the only way we can do this is as follows:

int num1, num2, num3, num4, sum;
Scanner in = new Scanner();
System.out.println(“Please enter a number”);
num1 = in.nextInt();
System.out.println(“Please enter a number”);
num2 = in.nextInt();
System.out.println(“Please enter a number”);
num3 = in.nextInt();
System.out.println(“Please enter a number”);
num4 = in.nextInt();
sum = num1 + num2 + num3 + num4;

This is very cumbersome -
And what if there were 100 numbers!

To solve this problem, essentially all programming languages have what are called arrays.


Example


Loops and Arrays

Using for-loops to set arrays:

for (int i = 0 ; i < 4 ; i++)	
	nums[i] = inputBox.getInteger(“Enter a number”);

Using for-loops for reading/printing arrays:

for (int i = 0 ; i < 4 ; i++)
	outputBox.printLine("i=" + i + ": " + nums[i]);

Example:

How might you use a loop to compute the average of an array of size 100 where each element of the array is a double?

double[] nums = new double[100]; // create array
for (int i = 0 ; i < nums.length ; i++) // load array
   nums[i] = 10* Math.random();

outputBox.printLine("array length is: " + nums.length);

double sum = 0;
for (int i = 0 ; i < nums.length ; i++) // sum elements
   sum = sum + nums[i];

outputBox.printLine("The average is " + sum/nums.length );

What about computing the standard deviation?


Bounds Checking

What happens if you try to access an array element that does not exist. For example

double[] nums = new double[100]; // create array
nums[100] = 2.; // ERROR

Java will crash and the error message you will get is:

java.lang.ArrayIndexOutOfBoundsException

Note: once an array is created, you cannot change the size of the array or the type of elements in the array. That is, you can't store a double in an integer array.


Listing the Elements

An array can also be declared and created by just listing the items to be included in the array:

double[] rate = {10.5, 11.7, 5.54};

This creates an array of 3 elements initialized to

rate[0]=10.5
rate[1]=11.7
rate[2]=5.54

Note that the size is set automatically to 3.


Arrays of Objects

In the above examples, we created arrays whose elements were of type integer. An integer is a primitive type. As one might expect, an array of primitive types is somewhat different than an array of objects.

Let's see how to create arrays of any type of object. For example, to create an array of Player objects you first must:

// create a reference to array called players
Player players[];

// create list of 10 references to Player Objects
players = new Player[10];

The above creates an array of references to Player objects. It does not actually create any Player objects!

To create the objects themselves:

for (int i = 0 ; i < 10 ; i ++)
   players[i] = new Player();


Example: A Very Simple Company

// represents a single employee
class Employee
{
   // Member Variables
	private String name;
	private double rate;

   // Methods
   public Employee()
   {
      name = inputBox.getString("Enter the name:");
      rate = inputBox.getFloat("Enter the hourly rate");
   }

   public String toString()
   {	
      String s = name + " earns $" + rate + " per hour." + "\n";
      return s;
   }
}

// represents a company containing up to 10 employees

class Company
{
   // Member Variables
   private employee[] emps; // create reference to 
	                      // array of employees
   // Methods
   public static void main (String args[])
   {
      Company c = new Company();
      c.printEmps();
   }

   public Company()
   {
      int num = inputBox.getInteger( 		
               "Enter the number of employees: ");
      emps = new employee[num]; // create employee array
      for (int i = 0; i < emps.length ; i++)		
         emps[i] = new employee(); // create employee elements
   }
	
   public String toString()
   {
      String s="";
      for (int i = 0; i < emps.length ; i++)		
         s += emps[i].toString() ;
      return s;
   }
}


Passing Arrays as Parameters

class testArray
{
   // Methods
   public static void main (String args[])
   {
      int A[] = {10,5,3,9,7}; // create an array
      printArray(A);
      changeArray(A);
      printArray(A);
   }

   public static void printArray(int [] B) { // pass array in 
                                             // as parameter	
      outputBox.printLine("Array: ");
      for (int i = 0; i < B.length ; i++)
         outputBox.print(B[i] + " ");
         outputBox.skipLine(2);
      }
	
      public static void changeArray(int [] C)
      {
         for (int i = 0; i < C.length ; i++)	
		C[i] = 2*i;
      }
}

In the above program, the address of A in main is copied into the parameter C when the changeArray method is called. The array itself is not copied, as shown below.


next lecture