Java Take-Off Step Two:


In which we're further sharpening our skills.
We start with an example of Threads being used to calculate Fibonacci numbers.

// Thread to calculate and print out the Fibonacci sequence of numbers 
class Fibonacci extends Thread
    // the minimum time to wait before updating 
    private static final long WAIT_TIME = 500;
    // the previous number in the sequence 
    private long previous;
    // the current number in the sequence 
    private long current;
    // an identifier for this sequence
    private char ident;
    // constructs a new Fibonacci sequence 
    public Fibonacci(char id)
	// set the identifier for this sequence
	ident = id;
	// initialize the first two numbers in the sequence 
	previous = 1;
	current = 1;
    // prints the next number in the sequence 
    private void printNext()
	System.out.print("(" + ident + ") " + current + ", ");
    // calculates the next number in the sequence; it is calculated as
    // the sum of the last two numbers in the sequence 
    private void update()
	long temp = current;
	current = previous + current;
	previous = temp;
    // execution code for the thread; this method is inherited from the
    // Thread class 
    public void run()
	// print the first two numbers in the sequence
	// get a reference to this thread
	Thread t = Thread.currentThread();
	// loop while the thread is active
	while(t == this)
		// update the sequence
		// once the current sequence value exceeds the largest long 
		// value, it will wrap around to negative values. once current
		// is negative, terminate this thread of execution
		if(current < 0L)
			System.out.println("\nNo more long values! " +
					   "Thread terminating...");
			t = null;
		// print out the next Fibonacci number
		// pause a bit                   
		catch(InterruptedException e) { }
    } // run

// creates a new Fibonacci sequence generators to test 
// multi-threaded applications
public class ThreadTest
    public static void main(String[] args)
	// start a few Fibonacci threads
	new Fibonacci('A').start();
	new Fibonacci('B').start();
	new Fibonacci('C').start();
EXERCISES Let's now see a Vector in action.

import java.util.*;

class VectorTest extends Object
    public static Vector getRandomScores()
	// create a random number generator
	Random rand = new Random();
	// generate between 500 and 1000 random scores
	int numElements = 500 + Math.abs(rand.nextInt())%501;
	// create a new Vector and fill it in with a bunch of random scores
	Vector v = new Vector(numElements);
	while(numElements > 0)
		// add an Integer between 0 and 2000
		v.add(new Integer(Math.abs(rand.nextInt())%2001));
	return v;
    // finds the greatest score within a vector of random scores
    public static void main(String[] args)
	int highestScore = 0;    // the highest score we've seen sofar
	// generate some random scores
	Vector scores = getRandomScores();               
	// cycle through the enumeration of the scores and pick out
	// the highest one
	for(Enumeration e = scores.elements(); e.hasMoreElements(); )
		Integer score = (Integer)(e.nextElement());
		if(score.intValue() > highestScore)
			highestScore = score.intValue();
	// print out the highest score
} // VectorTest
EXERCISES There are many other classes that implement data structures.

Here's a program that uses a HashTable to store images.

import java.applet.*;
import java.awt.*;
import java.awt.geom.*; 
import java.awt.event.*;
import java.util.*;

public class HashTest extends Applet implements ItemListener
    // Hashtable to add tile images
    private Hashtable imageTable;
    // a Choice of the various tile images
    private Choice selections;
    // assume tiles will have the same width and height; this represents
    // both a tile's width and height
    private int imageSize;
    // filename description of our images
    private final String[] filenames 
	= { "cement.gif",  "dirt.gif",  "grass.gif",         
	    "pebbles.gif", "stone.gif", "water.gif" };
    // initializes the Applet
    public void init()
	int n = filenames.length;
	// create a new Hashtable with n members
	imageTable = new Hashtable(n);
	// create the Choice 
	selections = new Choice();
	// create a Panel to add our choice at the bottom of the window
	Panel p = new Panel();
	p.add(selections, BorderLayout.SOUTH);
	// add the Choice to the applet and register the ItemListener     
	setLayout(new BorderLayout());
	add(p, BorderLayout.SOUTH);
	// allocate memory for the images and load 'em in
	for(int i = 0; i < n; i++)
		Image img = getImage(getCodeBase(), filenames[i]);
		while(img.getWidth(this) < 0);
		// add the image to the Hashtable and the Choice
		imageTable.put(filenames[i], img);
		// set the imageSize field
		if(i == 0)
			imageSize = img.getWidth(this);
    } // init
    // tiles the currently selected tile image within the Applet
    public void paint(Graphics g)
	// cast the sent Graphics context to get a usable Graphics2D object
	Graphics2D g2d = (Graphics2D)g;
	// save the Applet's width and height       
	int width = getSize().width;
	int height = getSize().height;
	// create an AffineTransform to place tile images
	AffineTransform at = new AffineTransform();
	// get the currently selected tile image
	Image currImage = (Image)imageTable.get(selections.getSelectedItem());
	// tile the image throughout the Applet
	int y = 0;
	while(y < height)
		int x = 0;
		while(x < width)
			at.setToTranslation(x, y);
			// draw the image           
			g2d.drawImage(currImage, at, this);
			x += imageSize;
		y += imageSize;
    } // paint
    // called when the tile image Choice is changed
    public void itemStateChanged(ItemEvent e)
	// our drop box has changed-- redraw the scene
} // HashTest
This program also needs an HTML file:


    <applet code=HashTest.class width=250 height=250></applet>

EXERCISES Here are the images being used: cement, dirt, grass, pebbles, stone, water.

You can find the applet at:
Use your browser, or the applet viewer, to view it.

Last updated: Apr 5, 2002 by Adrian German for A201/A597/I210/A348/A548/T540/NC009