Monday 29 August 2011

the java part 25

If you don't know how many items are going to be held in your array, you may be better off using something called an ArrayList. An ArrayList is a dynamic data structure, meaning items can be added and removed from the list. A normal array in java is a static data structure, because you stuck with the initial size of your array.
To set up an ArrayList, you first have to import the package from the java.util library:
import java.util.ArrayList;
You can then create a new ArrayList object:
ArrayList listTest = new ArrayList( );
Notice that you don't need any square brackets this time.
Once you have a new ArrayList objects, you can add elements to it with the add method:
listTest.add( "first item" );
listTest.add( "second item" );
listTest.add( "third item" );
listTest.add( 7 );
In between the round brackets of add you put what it is you want to add to the ArrayList. You can only add objects, however. The first three items we've added to the list above are String objects. The fourth item is a number. But this will be a number object of type Integer, rather than the primitive data type int.
Items in the list can be referenced by an Index number, and by using the get method:
listTest.get( 3 )
This line will get the item at Index position 3 on the list. Index numbers start counting at zero, so this will be the fourth item.
You can also remove items from an ArrayList. You can either use the Index number:
listTest.remove(2);
Or you can use the value on the list:
listTest.remove( "second item" );
Removing an item will resize the ArrayList, so you have to be careful when trying to get an item on the list when using its Index number. If we've removed item number 2, then our list above will contain only 3 items. Trying to get the item with the Index number 3 would then result in an error.
To go through each item in your ArrayList you can set up something called an Iterator. This class can also be found in the java.util library:
import java.util.Iterator;
You can then attach your ArrayList to a new Iterator object:
Iterator it = listTest.iterator( );
This sets up a new Iterator object called it that can be used to go through the items in the ArrayList called listTest. The reason for using an Iterator object is because it has methods called next and hasNext. You can use these in a loop:
while ( it.hasNext( ) ) {
System.out.println( it.next( ) );
}

The method hasNext returns a Boolean value. The value will be false if there are no more items in the ArrayList. The next method can be used to go through all the items in the list.
To test all this theory out, try the following code:
Java code showing an array list
Notice the line that prints out the entire list:
System.out.println( "Whole list=" + listTest );
This gives you a quick way to see which items are on your list, if it gets a bit too long.
When the code is run, the Output window will display the following:
first item
second item
third item
7
Whole list=[first item, third item, 7]
Position 1=third item
To sum up, then, use an ArrayList when you're not sure how many elements are going to be in a list of items.

We'll leave arrays, for now, and move on. In the next section, we'll tackle strings.

the java part 24

The arrays you have been using so far have only held one column of data. But you can set up an array to hold more than one column. These are called multi-dimensional arrays. As an example, think of a spreadsheet with rows and columns. If you have 6 rows and 5 columns then your spreadsheet can hold 30 numbers. It might look like this:
A representation of a 2-dimensional array
A multi dimensional array is one that can hold all the values above. You set them up like this:
int[ ][ ] aryNumbers = new int[6][5];
They are set up in the same way as a normal array, except you have two sets of square brackets. The first set of square brackets is for the rows and the second set of square brackets is for the columns. In the above line of code, we're telling Java to set up an array with 6 rows and 5 columns. To hold values in a multi-dimensional array you have to take care to track the rows and columns. Here's some code to fill the first rows of numbers from our spreadsheet image:
aryNumbers[0][0] = 10;
aryNumbers[0][1] = 12;
aryNumbers[0][2] = 43;
aryNumbers[0][3] = 11;
aryNumbers[0][4] = 22;
So the first row is row 0. The columns then go from 0 to 4, which is 5 items. To fill the second row, it would be this:
aryNumbers[1][0] = 20;
aryNumbers[1][1] = 45;
aryNumbers[1][2] = 56;
aryNumbers[1][3] = 1;
aryNumbers[1][4] = 33;
The column numbers are the same, but the row numbers are now all 1.
To access all the items in a multi-dimensional array the technique is to use one loop inside of another. Here's some code to access all our number from above. It uses a double for loop:
Java code showing how to use two for loops with a 2-dimensional array
The first for loop is used for the rows; the second for loop is for the columns. The first time round the first loop, the value of the variable i will be 0. The code inside of the for loop is another loop. The whole of this second loop will be executed while the value of the variable i is 0. The second for loop use a variable called j. The i and the j variables can then be used to access the array.
aryNumbers[ i ][ j ]
So the two loop system is used to go through all the values in a multi-dimensional array, row by row.

Exercise
Finish off the programme above where we are writing a programme to print out all the values from the spreadsheet. Your Output window should look something like this when you're done:
Output window of array code
Multi-dimensional arrays can be quite tricky, but mainly because it's hard to keep track of all your rows and columns! In the next part, you'll learn about array lists.

the java part 23

You can place strings of text into arrays. This is done in the same way as for integers:
String[ ] aryString = new String[5] ;
aryString[0] = "This";
aryString[1] = "is";
aryString[2] = "a";
aryString[3] = "string";
aryString[4] = "array";
The code above sets up a string array with 5 positions. Text is then assigned to each position in the array.
Here's a loop that goes round all the positions in the array, printing out whatever is at each position:
int i;
for ( i=0; i < aryString.length; i++ ) {
System.out.println( aryString[i] );
}

The loop goes round and round while the value in the variable called i is less than the length of the array called aryString.
When the above programme is run, the Output window will look like this:
Output window showing the results of a java string array
You can perform a sort on string arrays, just like you can with integers. But the sort is an alphabetical ascending one, meaning that "aa" will come first over "ab". However, Java uses Unicode characters to compare one letter in your string to another. This means that uppercase letter will come before lowercase ones. Try the following code:
Sorting a java string array
When the programme is run, the Output window will display the following:
Unexpected results in the output window
Although we've sorted the array, the word "This" comes first. If this were an alphabetical sort, you'd expect the word "a" to come first." And it does if all the letters are lowercase. In your programming code, change the capital "T" of "This" to a lowercase "t". Now run your programme again. The Output window will now display the following:
Alphabetic sort
As you can see, the word "this" is now at the bottom. We'll have a closer look at strings in the next section, so don't worry too much about them now. Instead, try these exercises.

Exercise
Set up an array to hold the following values, and in this order: 23, 6, 47, 35, 2, 14. Write a programme to get the average of all 6 numbers. (You can use integers for this exercise, which will round down your answer.)
Exercise
Using the above values, have your programme print out the highest number in the array.
Exercise
Using the same array above, have your programme print out only the odd numbers.


In the next lesson, you'll learn about multi-dimensional arrays in java.

the java part 22

Other inbuilt java methods allow you to sort your arrays. To use the sort method of arrays, you first need to reference a Java library called Arrays. You do this with the import statement. Try it with your aryNums programme. Add the following import statement:
import java.util.Arrays;
You code should look like ours below:
Importing the Arrays library
Now that you have imported the Arrays library, you can use the sort method. It's quite easy:
Arrays.sort( aryNums );
First you type the word "Arrays", then a dot. As soon as you type a dot, NetBeans will display a list of things you can do with arrays. Type the word "sort". In between a pair of round brackets, you then put the name of the array you want to sort. (Notice that you don't need any square brackets after the array name.)
And that's it - that's enough to sort the array! Here's some code to try out:
Java code showing how to sort an array
The for loop at the end will go round and round printing out the values in each array position. When the code is run, the Output will look like this:
Output window showing the results of the sort
As you can see, the array has been sorted in ascending order.
Sorting in descending order, however, is only possible either by writing your own sorting code, or converting your array to Integer objects then importing from the Collections library. If you need to a descending sort, here's some code that does just that (skip this code, if you want):

Java code for a descending array sort
All a bit messy, I'm sure you'll agree!

In the next lesson, we'll take a look at arrays and strings.

the java part 21

Arrays come into their own with loops. You have seen in the previous section that to assign values to array positions, you did this:
aryNums[0] = 10;
But that's not terribly practical if you have a lot of numbers to assign to an array. As an example, imagine a lottery programme that has to assign the numbers 1 to 49 to positions in an array. Instead of typing a long list of array positions and values you can use a loop. Here's some code that does just that:
A Java array used in a loop
So we set up an array to hold 49 integer values. Then comes the loop code. Notice the end condition of the loop:
i < lottery_numbers.length
Length is a property of array objects that you can use to get the size of the array (how many positions it has). So this loop will keep going round and round while the value in the variable i is less than the size of the array.
To assign values to each position in the array, we have this line:
lottery_numbers[i] = i + 1;
Instead of a hard-code value between the square brackets of the array name, we have the variable called i. This increases by 1 each time round the loop, remember. Each array position can then be accessed just by using the loop value. The value that is being assigned to each position is i + 1. So again, it's just the incremented loop value, this time with 1 added to it. Because the loop value is starting at 0, this will give you the numbers 1 to 49.
The other line in the loop just prints out whatever value is in each array position.
(If you wanted, you could then write code to jumble up the numbers in the array. Once you have jumbled up the values, you could then take the first 6 and use them as the lottery numbers. Write another chunk of code that compares a user's 6 numbers with the winning numbers and you have a lottery programme!)
In the next part, you'll see how to sort your arrays.