On completion of this section you will know
Up to now we have used single variables, and in all cases so far they have served us very well. On the other hand supposing that we were dealing with an application that calculated the average daily temperature for a month, then using the variables that we are so far familiar with we could start as follows:
|
double day1, day2, day3………day31; |
Next we would have to put values into those 31 variables. At its simplest this could be:
|
day1 = 22; |
|
day2 =24; |
|
. |
|
. |
|
. |
|
day31 = 28; |
Already it is becoming clear that this style of programming is becoming very clumsy. Now to compound this problem, supposing we had to compute the average values for a whole year!
The way out of this problem is to use arrays. An array is a group of variables which share the same name and are differentiated from each other by an index value.
In order to create an array for our monthly temperatures we would do as follows:
|
double days[] = new double[31]; |
Logically this would create a structure like the following in memory:
|
days |
[0] |
|
|
|
[1] |
|
|
|
[2] |
|
|
|
. |
|
|
|
. |
|
|
|
. |
|
|
|
[29] |
|
|
|
[30] |
|
Here we have one array called days which holds 31 double variables, each identified by its index value. Notice that the array starts indexing at 0 and thus in a 31 element array the highest index is 30.
Let us first look at a very simple array of double values where we simply create the array, assign values to its elements and finally print out its contents.
Listing 11.1
|
1 |
public class Untitled3 |
|
2 |
{ |
|
3 |
public static void main(String[] args) |
|
4 |
{ |
|
5 |
double values[] = new double[10]; |
|
6 |
for(int i = 0;i<10;i++) |
|
7 |
values[i] = Math.random()*10; |
|
8 |
for(int i = 0;i<10;i++) |
|
9 |
System.out.println(values[i]); |
|
10 |
} |
|
11 |
} |
Here at line 5 a ten element array is created. At lines 6 and 7 a for loop is used to put values into its elements. At the start the loop counter, i, has a value of 0 and thus at line 7 a random number is assigned to values[0]. Next the counter is incremented to 1 and once again at line 7 another random number is assigned to values[1]. This process continues until the counter has reached a value of 9 and a value is assigned to value[9]. The loop then terminates.
Finally, the loop at lines 8 and 9 prints out the values in the array.
This is, of course, an extremely simple sample of arrays, because there is a lot of other processing that we can do on them. One is those is to sort them which is what we do in Listing 11.2 below.
Listing 11.2
|
1 |
public class Untitled3 |
|
2 |
{ |
|
3 |
public static void main(String[] args) |
|
4 |
{ |
|
5 |
double temp; |
|
6 |
boolean sorted; |
|
7 |
double values[] = new double[10]; |
|
8 |
for(int i = 0;i<10;i++) |
|
9 |
values[i] = Math.random()*10; |
|
10 |
for(int i = 0;i<10;i++) |
|
11 |
System.out.println(values[i]); |
|
12 |
do |
|
13 |
{ |
|
14 |
sorted = true; |
|
15 |
for(int i = 0;i < 9; i++) |
|
16 |
{ |
|
17 |
if(values[i]>values[i+1]) |
|
18 |
{ |
|
19 |
temp = values[i]; |
|
20 |
values[i] = values[i+1]; |
|
21 |
values[i+1] = temp; |
|
22 |
sorted = false; |
|
23 |
} |
|
24 |
} |
|
25 |
}while(!sorted); |
|
26 |
for(int i = 0;i<10;i++) |
|
27 |
System.out.println(values[i]); |
|
28 |
} |
|
29 |
} |
This example is almost identical to the previous one up until line 11. Lines 12 – 25, however, contain a do..while loop which sorts the array using the bubble sort algorithm. A simple explanation of this algorithm is as follows:
Compare the first two elements of the array and if they are out of order then swap them.
Do the same with the second and third elements.
Continue like this until all elements have been compared.
If any pair of elements have been swapped then go back to step 1
Finally lines 26 and 27 print out the sorted array.
Listing 11.3 below is almost identical to Listing 11.2 except that it processes an array of Strings instead of numbers. As the overall logic of both is identical we shall only comment on the points where they differ.
Listing 11.3
|
1 |
public class Untitled1 |
|
2 |
{ |
|
3 |
public static void main(String[] args) |
|
4 |
{ |
|
5 |
String temp; |
|
6 |
boolean sorted; |
|
7 |
String values[] =
{"Tom","Dick","Harry","Tim", |
|
8 |
"Pat","Joe","Annie","Maggie"}; |
|
9 |
for(int i = 0;i<values.length;i++) |
|
10 |
System.out.println(values[i]); |
|
11 |
Do |
|
12 |
{ |
|
13 |
sorted = true; |
|
14 |
for(int i = 0;i < values.length-1;
i++) |
|
15 |
{ |
|
16 |
if(values[i].compareTo(
values[i+1])>0) |
|
17 |
{ |
|
18 |
temp = values[i]; |
|
19 |
values[i] = values[i+1]; |
|
20 |
values[i+1] = temp; |
|
21 |
sorted = false; |
|
22 |
} |
|
23 |
} |
|
24 |
}while(!sorted); |
|
25 |
for(int i = 0;i<values.length;i++) |
|
26 |
System.out.println(values[i]); |
|
27 |
} |
|
28 |
} |
Line 7 shows a different way of constructing an array. This way does not apply exclusively to String values. In Listing 11.2 we could replace lines 7, 8, 9 with
|
7 |
double values[] = {9,8,7,6,5,4,3,2,1,0}; |
We would still have an array of numbers, although this new array can hardly be described as random.
The other difference is in line 16 where we compare if two Strings are out of alphabetical sequence. In this case we cannot use the mathematical “greater than” operand, since no one piece of text is numerically greater than another. Instead we have to use the compareTo method of the String class. If this method finds that two strings are out of alphabetical sequence it returns a positive number, which is what we are testing for in line 16.
We are finally at the stage where we can explain the final part of the signature of the method main – the argument String[] args. This is simply an array of Strings that we can use to pass values to the programme from outside. Listing 11.4 below shows a very simple use of this array where it just simply prints out the value of the arguments.
Listing 11.4
|
1 |
public class Untitled4 |
|
2 |
{ |
|
3 |
public static void main(String[] args) |
|
4 |
{ |
|
5 |
for(int i = 0;i<args.length;i++) |
|
6 |
System.out.println(args[i]); |
|
7 |
} |
|
8 |
} |
Below is a much more practical use of the args array. In listing 11.5 we have modified the class Pay so that we can pass data to hours and rate using String values.
Listing 11.5
|
1 |
public class Pay |
|
2 |
{ |
|
3 |
private double hours, rate, gross, tax,
nett; |
|
4 |
private boolean validHours, validRate,
calculateOK; |
|
5 |
public void setHours(String h) |
|
6 |
{ |
|
7 |
double temp; |
|
8 |
try |
|
9 |
{ |
|
10 |
temp = Double.parseDouble(h.trim()); |
|
11 |
setHours(temp); |
|
12 |
} |
|
13 |
catch(NumberFormatException e) |
|
14 |
{ |
|
15 |
validHours = false; |
|
16 |
} |
|
17 |
} |
|
18 |
public void setRate(String r) |
|
19 |
{ |
|
20 |
double temp; |
|
21 |
try |
|
22 |
{ |
|
23 |
temp = Double.parseDouble(r.trim()); |
|
24 |
setRate(temp); |
|
25 |
} |
|
26 |
catch(NumberFormatException e) |
|
27 |
{ |
|
28 |
validRate = false; |
|
29 |
} |
|
30 |
} |
|
31 |
public void setHours(double h) |
|
32 |
{ |
|
33 |
if((h>=5) && (h<=60)) |
|
34 |
{ |
|
35 |
hours = h; |
|
36 |
validHours = true; |
|
37 |
} |
|
38 |
else |
|
39 |
validHours = false; |
|
40 |
} |
|
41 |
public void setRate(double r) |
|
42 |
{ |
|
43 |
if((r>=8) && (r<=50)) |
|
44 |
{ |
|
45 |
rate = r; |
|
46 |
validRate = true; |
|
47 |
} |
|
48 |
else |
|
49 |
validRate = false; |
|
50 |
} |
|
51 |
public String toString() |
|
52 |
{ |
|
53 |
String msg = "Hours = "; |
|
54 |
msg =
msg.concat(Double.toString(getHours())); |
|
55 |
msg = msg.concat("\nRate = "); |
|
56 |
msg =
msg.concat(Double.toString(getRate())); |
|
57 |
msg = msg.concat("\nGross = "); |
|
58 |
msg =
msg.concat(Double.toString(getGross())); |
|
59 |
msg = msg.concat("\nTax = "); |
|
60 |
msg = msg.concat(Double.toString(getTax())); |
|
61 |
msg = msg.concat("\nNett = "); |
|
62 |
msg =
msg.concat(Double.toString(getNett())); |
|
63 |
return msg; |
|
64 |
} |
Again only part of the class is shown – the parts that we have modified. The main modification that has occurred is that the methods setHours and setRate are overloaded. The overloadings of both simply take a String argument instead of a double argument. Again in the bodies we only have a try..catch construct. In the try body an attempt is made to convert the String argument into a double value. If this is successful the set method that takes a double argument is called. If an exception is thrown, however, the body of the catch simply sets the appropriate flat to false.
We have introduced another modification which is not directly related to array processing but is very conducive to good programming techniques on the OO area – the introduction of the method toString. By now you may have noticed that most of Java’s own native classes have a method called toString. The purpose of this method is to return a String value which describes the state of an object of the class. What form this description takes depends on the class itself. In our case we shall use the method to display the values of the class variables that directly relate to the payroll. We do this by using the concat method of the String class to build up the String variable msg and at the end return the result of the concatenation.
Listing 11.6 shows us how to use the args array to send values to the new version of the Pay class.
Listing 11.6
|
1 |
public class Untitled2 |
|
2 |
{ |
|
3 |
public static void main(String[] args) |
|
4 |
{ |
|
5 |
Pay p = new Pay(); |
|
6 |
p.setHours(args[0]); |
|
7 |
p.setRate(args[1]); |
|
8 |
p.calculate(); |
|
9 |
System.out.println(p.toString()); |
|
10 |
} |
|
11 |
} |
An array is a group of variables that have a common name and are distinguished from each other by their individual indexes. Although all of the variables in any one array must be of the same data type, we can have an array of any data type we wish. Arrays can be sorted into any order appropriate to their data type.
Copy Listing 11.2 into your computer, then compile and run it. Next change the size of the array and recompile and run it. Remember that when you alter the size of the array, any code that processes that array must be altered accordingly. Also remember that the size of the array cannot be zero or negative.
Notice that when you alter the size of the array you have to alter the code in lines 7, 8, 10, 15 and 26. Now try adding an extra line so that you have to only alter that line when altering the size of the array.
Once you have been able to successfully alter the array and fully process the altered version now try printing out the array in reverse order
Now modify the code so that you can get the sum and the average of all of the elements in the array. These values are printed out at the end
For the really adventurous try further modifying the code so that the maximum and minimum values in the array are calculated and printed.
Next copy Listing 11.3 into your computer. Alter this so that the data for the String array comes in through the argument args. (You can dispense with the variable values in this case.) Ensure that the code is able fully sort and print out an array of any size.
1. Define an array.
2. Describe a situation where an array is more useful than regular variables.
3. Describe some of the processing that can be done on arrays that would be more difficult on normal variables.