Top: Index Previous: Conditionals and Inheritance Up: Index Next: Properties

CSC8303 -- Bioinformatics Programming in Java

Arrays and Exceptions

The purpose of this exercise is:

exclaim
  • To use an array.
  • Gain familiarity with exceptions.
  • Revise control flow structures and inheritance

Using an array

Arrays are an important feature of many languages; sometimes, we don't want to give a new label to each variable that we store. Maybe, we don't know in advance how many we are going to need. This is where arrays come in.

You can read about arrays in the Java Tutorial. As with most of the rest of the exercises, we are going to investigate this by animating something.

act
  • Create 2 new classes in the animate package called ColourChange.java and ColourChangeTest.java.
  • Ensure that the class ColourChange inherits from the class Animate.
  • Add this code to ColourChange.java.
    public void animateColourCircle(){
        Circle c = new Circle();
        c.makeVisible();

        Colour[] colours = Colour.values();
    }
  • And this to ColourChangeTest.java
    public static void main( String[] args )
            throws  InterruptedException {

        ColourChange c = new ColourChange();
        c.setAnimateStep( 500 );
        c.animateColourCircle();

        Thread.sleep( 2000 );
        System.exit( 0 );
    }
  • There are 6 colours. Write a for loop which changes the colour of the Circle object to each in turn.
  • Do not forget to call animateStep() after each change in the colour.
  • 6 Colours is not very many; it all happens a bit quickly. Put in another for loop to run through all of the colours 5 times.
exclaim If you get odd things happening in the last section, consider carefully the names of your variables.

What happens when things go wrong

You probably wrote a for loop which looked something like this:

for( int i = 0; i < 6; i++ ){
   // stuff in here
}

Which works fine.

actTry changing the 6 to a 10.

Now the code crashes; you should get something like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
        at animate.ColourChange.animateColourCircle(ColourChange.java:25)
        at animate.ColourChangeTest.main(ColourChangeTest.java:18)

Again, the Java tutorial explains a great deal about exceptions and why we would want to use them.

We can use them to build an alternative for loop if we choose; this is not particularly recommended but demonstrates a point. It also shows usage of a while loop.

act Replace the for loop with this code:
           // strange mechanism for doing a for loop.
           // this code is NOT recommended for general use.
           try{
                int i = 0;
                while (true) {
                    c.changeColour(colours[i]);
                    animateStep();
                    i++;
                }
            }
            catch ( ArrayIndexOutOfBoundsException abe ){
                // carry on...
                // but at least print something out because ignoring
                // exceptions is very bad practice.
                System.out.println( "Reached end of array" );
            }
quest
  • Why is this a bad way of writing a for loop? I can think of 3 main reasons.

Although this example is a little pathological, exceptions are very useful. They tell you what sort of things could go wrong, and give you a chance to deal with them; handling errors is critical in programming.

At times, most programmers get irritated with exceptions. NullPointerException and IOException are some of the most common in Java.

A better for loop

One characteristic of an array is that they are objects that know how long they are. One way of improving our for loop is to use this characteristic. To get the length of an array, we use a call like this:

   colours.length;
act
  • Put back your original for loop.
  • Replace "6" with colours.length.

Now your code should run again; importantly, we could add a new Colour and the code would still work correctly. In fact, this pattern used to be the standard way of accessing all the elements of an array. The Java language has now been updated and there is a better way still, which is called the foreach loop 1.

act Try this instead:
   for( Colour colour: colours ){
   }
quest

What advantages does the foreach loop have over the older for loop?

log The final version of ColourChange.java is the coursework for this exercise.

1. Why foreach? Well, many languages use a keyword called foreach to make this form of loop. When Java was updated they choose not to. This avoided introducing a new keyword which could have broken older programs.


Top: Index Previous: Conditionals and Inheritance Up: Index Next: Properties