Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Learning objectives<br />
<strong>Arrays</strong><br />
By the end of this lecture you should be able to:<br />
• cre<strong>at</strong>e arrays of primitive types;<br />
• use loops to process arrays;<br />
• use an enhanced for loop to process an array;<br />
• use arrays as method inputs and outputs;<br />
• develop routines for accessing and manipul<strong>at</strong>ing arrays.<br />
ESSENTIAL READING: Char<strong>at</strong>an and Kans (Chapter 5)<br />
Introduction<br />
• SO FAR: variables cre<strong>at</strong>ed to hold a single item of d<strong>at</strong>a.<br />
• NOW: How to cre<strong>at</strong>e and handle a very large number of d<strong>at</strong>a items?<br />
• MAYBE: declare as many variables as you need?<br />
public class Temper<strong>at</strong>ureReadings<br />
{<br />
}<br />
public st<strong>at</strong>ic void main(String[] args)<br />
{<br />
}<br />
// declare 7 variables to hold readings<br />
double temper<strong>at</strong>ure1, temper<strong>at</strong>ure2, temper<strong>at</strong>ure3, temper<strong>at</strong>ure4,<br />
temper<strong>at</strong>ure5, temper<strong>at</strong>ure6, temper<strong>at</strong>ure7;<br />
// more code will go here<br />
How to enter 7 temper<strong>at</strong>ure readings?<br />
• Try using a for loop?<br />
for (int i=1; i
• Ideally each variable should have the same name.<br />
• This is exactly wh<strong>at</strong> an array allows us to do.<br />
Wh<strong>at</strong> is an array?<br />
• An array is a d<strong>at</strong>a type th<strong>at</strong> stores a collection of items.<br />
• These items are sometimes referred to as the elements of the array.<br />
• All the elements stored in a particular array must be of the same type but there is no<br />
restriction on which type this is.<br />
For example<br />
o arrays can be used to hold a collection of int values;<br />
o or a collection of char values;<br />
o BUT they cannot be used to hold a mixture of int and char values.<br />
Cre<strong>at</strong>ing an array<br />
• Array cre<strong>at</strong>ion is a two-stage process:<br />
1. declare an array variable;<br />
2. alloc<strong>at</strong>e memory to store the array elements.<br />
Declaring an array variable<br />
Example: an array to hold a collection of integer variables:<br />
int[] someArray;<br />
• So, to declare an array temper<strong>at</strong>ure containing double values:<br />
double[] temper<strong>at</strong>ure;<br />
Alloc<strong>at</strong>ing memory to store the array elements<br />
• Need to st<strong>at</strong>e<br />
o the size of the array ;<br />
o the type of each individual array element .<br />
• The array type and size are then put together with a special new oper<strong>at</strong>or.<br />
Example: an array of 10 integers:<br />
arrayName = new int[10];<br />
23
Returning to the temper<strong>at</strong>ure array<br />
• The temper<strong>at</strong>ure array holds seven double values:<br />
temper<strong>at</strong>ure = new double[7];<br />
• The two stages of array cre<strong>at</strong>ion can be combined into one step as follows:<br />
double[ ] temper<strong>at</strong>ure = new double[7];<br />
The effect on computer memory of declaring an array<br />
Computer Memory<br />
temper<strong>at</strong>ure<br />
item of type 'double'<br />
item of type 'double'<br />
item of type 'double'<br />
item of type 'double'<br />
item of type 'double'<br />
item of type 'double'<br />
item of type 'double'<br />
24<br />
Java Instructions<br />
temper<strong>at</strong>ure = new double[7];
Naming the array elements<br />
• Each element in an array shares the same name as the array.<br />
• The individual elements are then uniquely identified by an additional index value.<br />
• So the first element in the temper<strong>at</strong>ure array is temper<strong>at</strong>ure[0], the second<br />
temper<strong>at</strong>ure[1] and so on:<br />
0 1 2 3 4 5 6<br />
Initializing an array<br />
• An example:<br />
double[] temper<strong>at</strong>ure = {9, 11.5, 11, 8.5, 7, 9, 8.5} ;<br />
• This is the only instance in which all the elements of an array can be assigned explicitly<br />
by listing out the elements in a single assignment st<strong>at</strong>ement.<br />
• Once an array has been cre<strong>at</strong>ed, elements must be accessed individually.<br />
Accessing array elements<br />
• Array can be used like any other variable of the given type in Java.<br />
• The assignment oper<strong>at</strong>or can be used to enter a value.<br />
• You must specify which element to place the value in.<br />
For example<br />
• Allowing the user of the program to enter the value of the first temper<strong>at</strong>ure:<br />
temper<strong>at</strong>ure[0] = sc.nextDouble();<br />
25<br />
temper<strong>at</strong>ure
More examples of accessing array elements<br />
• Printing out the value of the sixth array element:<br />
System.out.println(temper<strong>at</strong>ure[5]); // index 5 is the sixth element!<br />
• Doubling the value of the fifth temper<strong>at</strong>ure.<br />
temper<strong>at</strong>ure[4] = temper<strong>at</strong>ure[4] * 2;<br />
• Checking if the temper<strong>at</strong>ure for the third day was a hot temper<strong>at</strong>ure:<br />
if (temper<strong>at</strong>ure[2] >= 18)<br />
{<br />
}<br />
System.out.println("it was hot today");<br />
Using a variable as the array index<br />
• The array index does not need to be a literal number such as 5 or 2; it can be any<br />
expression th<strong>at</strong> evalu<strong>at</strong>es to an integer.<br />
• More often than not an integer variable is used to access an array element.<br />
Example:<br />
• Assume th<strong>at</strong> i is some integer variable:<br />
System.out.println(temper<strong>at</strong>ure[i]); // index is a variable<br />
• If the value of i is 4 then this will display temper<strong>at</strong>ure[4], if the value of i is 6<br />
then this will display temper<strong>at</strong>ure[6], and so on.<br />
26
Using a loop counter as an array index<br />
Example<br />
• Entering all seven temper<strong>at</strong>ure readings:<br />
for(int i = 0; i
}<br />
}<br />
}<br />
System.out.println("enter max temper<strong>at</strong>ure for day " + (i+1));<br />
temper<strong>at</strong>ure[i] = sc.nextDouble();<br />
// display temper<strong>at</strong>ures<br />
System.out.println(); // blank line<br />
System.out.println("***TEMPERATURES ENTERED***");<br />
for (int i = 0; i < temper<strong>at</strong>ure.length; i++)<br />
{<br />
}<br />
Passing arrays as parameters<br />
System.out.println("day "+(i+1)+" "+ temper<strong>at</strong>ure[i]);<br />
• Program 5.1 contains all the processing within the main method.<br />
• Now we will cre<strong>at</strong>e two helper methods, enterTemps and displayTemps, to enter<br />
and display temper<strong>at</strong>ures respectively.<br />
Program 5.2<br />
import java.util.*;<br />
public class Temper<strong>at</strong>ureReadings2<br />
{<br />
public st<strong>at</strong>ic void main(String[] args)<br />
{<br />
}<br />
double[ ] temper<strong>at</strong>ure = new double[7];<br />
enterTemps(temper<strong>at</strong>ure); // call helper method<br />
displayTemps(temper<strong>at</strong>ure); // call helper method<br />
// helper method to enter temper<strong>at</strong>ures<br />
priv<strong>at</strong>e st<strong>at</strong>ic void enterTemps(double[] temper<strong>at</strong>ureIn)<br />
{<br />
}<br />
Scanner sc = new Scanner(System.in);<br />
for (int i = 0; i < temper<strong>at</strong>ureIn.length; i++)<br />
{<br />
}<br />
System.out.println("enter max temper<strong>at</strong>ure for day " + (i+1));<br />
temper<strong>at</strong>ureIn[i] = sc.nextDouble();<br />
28
}<br />
// helper method to display temper<strong>at</strong>ures<br />
priv<strong>at</strong>e st<strong>at</strong>ic void displayTemps(double[] temper<strong>at</strong>ureIn)<br />
{<br />
}<br />
System.out.println();<br />
System.out.println("***TEMPERATURES ENTERED***");<br />
for (int i = 0; i < temper<strong>at</strong>ureIn.length; i++)<br />
{<br />
}<br />
System.out.println("day "+(i+1)+" "+ temper<strong>at</strong>ureIn[i]);<br />
The effect on computer memory of passing an array as a parameter<br />
• In the case of arrays, the value sent as a parameter is not a copy of each array element<br />
but, instead, a copy of the array reference.<br />
temper<strong>at</strong>ure<br />
Computer Memory<br />
temper<strong>at</strong>ureIn<br />
item of type double<br />
item of type double<br />
item of type double<br />
item of type double<br />
item of type double<br />
item of type double<br />
item of type double<br />
29<br />
Java Instructions<br />
main(String[] args)<br />
{<br />
}<br />
// call method with local array<br />
enterTemps(temper<strong>at</strong>ure);<br />
// method receives array reference<br />
enterTemps(double[] temper<strong>at</strong>ureIn)<br />
{<br />
}<br />
// code here using temper<strong>at</strong>ureIn
Returning an array from a method<br />
• Reconsider the enterTemps method from program 5.2.<br />
• Since this method fills the original array sent in as a parameter, it does not need to<br />
return a value – its return type is therefore void.<br />
• An altern<strong>at</strong>ive approach would be not to send an array to this method but, instead, to<br />
cre<strong>at</strong>e an array within this method and fill this array with values.<br />
• This array can then be returned from the method:<br />
// this method receives no parameter but returns an array of doubles<br />
priv<strong>at</strong>e st<strong>at</strong>ic double[] enterTemps()<br />
{<br />
}<br />
Scanner sc = new Scanner(System.in);<br />
// cre<strong>at</strong>e an array within this method<br />
double[ ] temper<strong>at</strong>ureOut = new double[7];<br />
// fill up the array cre<strong>at</strong>ed in this method<br />
for (int i = 0; i < temper<strong>at</strong>ureOut.length; i++)<br />
{<br />
}<br />
System.out.println("enter max temper<strong>at</strong>ure for day " + (i+1));<br />
temper<strong>at</strong>ureOut[i] = sc.nextDouble();<br />
// send back the array cre<strong>at</strong>ed in this method<br />
return temper<strong>at</strong>ureOut;<br />
Now we need to modify the main method<br />
• The enterTemps method now returns an array.<br />
• We need to modify the main method so th<strong>at</strong> the returned array value is used to set the<br />
value of the original temper<strong>at</strong>ure array :<br />
// just declare the ‘temper<strong>at</strong>ure’ array but do not alloc<strong>at</strong>e it memory yet<br />
double[ ] temper<strong>at</strong>ure;<br />
// ‘temper<strong>at</strong>ure’ array is now set to the return value of ‘enterTemps’<br />
temper<strong>at</strong>ure = enterTemps();<br />
• We have not sized the temper<strong>at</strong>ure array once it has been declared.<br />
• Instead the temper<strong>at</strong>ure array will be set to the size of the array returned by<br />
enterTemps, and it will contain all the values of the array returned by<br />
enterTemps.<br />
30
The enhanced 'for' loop<br />
• Java 5 provides an enhanced version of the for loop to simplify array processing.<br />
• This loop requires no counter.<br />
Example<br />
• To display on the screen each value from the temper<strong>at</strong>ure array:<br />
/* the enhanced for loop iter<strong>at</strong>es through elements of an array without the<br />
need for an array index */<br />
for (double item : temper<strong>at</strong>ure) // variable holds consecutive array elenents<br />
{<br />
}<br />
System.out.println(item);<br />
• The loop header is to be read ad “for each item in the temper<strong>at</strong>ure array”.<br />
When to use the enhanced 'for' loop<br />
• You should use an enhanced for loop only when<br />
o you wish to access the entire array (and not just part of the array);<br />
o you wish to read the elements in the array, not modify them;<br />
o you do not require the array index for additional processing.<br />
Some useful array methods<br />
• We will develop some methods for processing an array.<br />
• We will use a simple integer array for this example.<br />
• Here is the outline of the program we are going to write in order to do this :<br />
import java.util.*;<br />
public class SomeUsefulArrayMethods<br />
{<br />
public st<strong>at</strong>ic void main (String[] args)<br />
{<br />
Scanner sc = new Scanner(System.in);<br />
int[] someArray; // declare an integer array<br />
// ask user to determine size of array<br />
System.out.println("How many elements to store?");<br />
int size = sc.nextInt();<br />
// size array now<br />
31
}<br />
}<br />
someArray = new int[size];<br />
// call methods here<br />
// methods to process an array here<br />
Array maximum: design<br />
• Method to find the maximum value in an array:<br />
SET result TO first value in array<br />
LOOP FROM second element in array TO last element in array<br />
BEGIN<br />
IF current element > result<br />
BEGIN<br />
SET result TO current element<br />
END<br />
END<br />
RETURN result<br />
Array maximum: implement<strong>at</strong>ion<br />
priv<strong>at</strong>e st<strong>at</strong>ic int max (int[] arrayIn)<br />
{<br />
}<br />
int result = arrayIn[0]; // set result to the first value in the array<br />
// this loops runs from the 2nd item to the last item in the array<br />
for (int i=1; i < arrayIn.length; i++)<br />
{<br />
}<br />
{<br />
}<br />
if (arrayIn[i] > result)<br />
return result;<br />
result = arrayIn[i]; // reset result to new maximum<br />
32
Array maximum: an altern<strong>at</strong>ive implement<strong>at</strong>ion<br />
// this version of ‘max’ makes use of an enhanced ‘for’ loop<br />
priv<strong>at</strong>e st<strong>at</strong>ic int max (int[] arrayIn)<br />
{<br />
}<br />
int result = arrayIn[0]; // set result to the first value in the array<br />
// this loops runs through all items in the array<br />
for (int currentElement: arrayIn)<br />
{<br />
}<br />
{<br />
}<br />
if (currentElement > result)<br />
return result;<br />
Array summ<strong>at</strong>ion: design<br />
result = currentElement; // reset result to new maximum<br />
• Method th<strong>at</strong> calcul<strong>at</strong>es the total of all the values in the array:<br />
SET total TO zero<br />
LOOP FROM first element in array TO last element in array<br />
BEGIN<br />
SET total TO total + value of current element<br />
END<br />
RETURN total<br />
Array summ<strong>at</strong>ion: implement<strong>at</strong>ion<br />
priv<strong>at</strong>e st<strong>at</strong>ic int sum (int[] arrayIn)<br />
{<br />
}<br />
int total = 0;<br />
for (int currentElement : arrayIn)<br />
{<br />
}<br />
total = total + currentElement;<br />
return total;<br />
33
Array membership: design<br />
• A method to determine whether or not an array contains a particular value:<br />
LOOP FROM first element in array TO last element in array<br />
BEGIN<br />
IF current element = item to find<br />
BEGIN<br />
EXIT loop and RETURN true<br />
END<br />
END<br />
RETURN false<br />
Array membership: implement<strong>at</strong>ion<br />
priv<strong>at</strong>e st<strong>at</strong>ic boolean contains (int[] arrayIn, int valueIn)<br />
{<br />
}<br />
// enhanced ‘for’ loop used here<br />
for (int currentElement : arrayIn)<br />
{<br />
}<br />
if (currentElement == valueIn)<br />
{<br />
}<br />
return true; // exit loop early if value found<br />
return false; // value not present<br />
Array search: design<br />
• A method to determine the position of an item within the list:<br />
LOOP FROM first element in array TO last element in array<br />
BEGIN<br />
IF current element = item to find<br />
BEGIN<br />
EXIT loop and RETURN current index<br />
END<br />
END<br />
RETURN -999<br />
34
Array search: implement<strong>at</strong>ion<br />
priv<strong>at</strong>e st<strong>at</strong>ic int search (int[] arrayIn, int valueIn)<br />
{<br />
}<br />
// enhanced ‘for’ loop should not be used here!<br />
for (int i=0; i < arrayIn.length; i++)<br />
{<br />
}<br />
if (arrayIn[i] == valueIn)<br />
{<br />
}<br />
return i; // exit loop with array index<br />
return -999; // indic<strong>at</strong>es value not in list<br />
35
Programming exercise<br />
1. Consider a room booking program th<strong>at</strong> keeps track of the capacity of 5 rooms in a<br />
building.<br />
a) Declare and initialise an array, rooms, to hold the following capacities:<br />
Room 1: capacity 30<br />
Room 2: capacity 25<br />
Room 3: capacity 50<br />
Room 4: capacity 30<br />
Room 5: capacity 40<br />
b) Write a method, displayRooms, th<strong>at</strong> accepts the array of room capacities<br />
and displays the capacity of each room.<br />
c) Add an instruction in main to call the displayRooms method.<br />
Advanced:<br />
d) Write a method, checkAllRooms, which accepts the array of rooms and a<br />
required capacity and displays all rooms th<strong>at</strong> meet th<strong>at</strong> capacity.<br />
e) Add an instruction in main to call the checkAllRooms method.<br />
f) Write a method, changeCapacity, which accepts the array of rooms, a<br />
room number and a new capacity for this room and upd<strong>at</strong>es the capacity of<br />
the given room.<br />
g) Add instructions in main to call the checkCapacity method and then the<br />
displayRooms method to check to check th<strong>at</strong> the given capacity has been<br />
changed.<br />
h) We-write this program so th<strong>at</strong> it us menu driven and add any other options<br />
you wish (such as checking the capacity of a single room).<br />
36