package l20; import java.util.Scanner; /** * Testing heap functionality and visualising * its structure. * * @author Michael Albert * @author Lech Szymanski * */ public class Test { /** DELAY controls the speed of visualisation - larger number * means slower visualisation. */ static final int DELAY = 500; /** The upper end of the range (from 0) where * random numbers are generated. */ static final int MAX_NUMBER = 1000; /** * This is the main method which tests the ArrayHeap. * * @param args Unused. */ public static void main(String[] args) { /** Instantiate the visualiser */ GraphicalHeap visualiser = new GraphicalHeap(DELAY); /** Create ArrayHeap of Integer with initial capacity of 1. * Note that we are using Integer (object) and not int (primitive) - * that because of the requirement on the template type T in the * ArrayHeap to comform to Comparable interface - that it needs to * be an object that implements compareTo method...and int is not an * object. */ ArrayHeap h = new ArrayHeap(1); /** Instantiate scanner to accept data from the terminal. */ Scanner in = new Scanner(System.in); while (true) { /** Ask for number elements to add to the heap, if 0 quit. */ System.out.println("How many elements should I add? (0 to quit)"); int n = Integer.parseInt(in.next()); if (n <= 0) { break; } /** For each of the elements to be added, generate random number * and add it to the heap. Print the resulting heap (as an array) * and show the visualisation of the heap. */ for (int i = 0; i < n; i++) { int v = (int) ((Math.random() * MAX_NUMBER)); h.add(v); System.out.println("Adding " + v); System.out.println(h); visualiser.show(h); } } /** Remove all the items from the heap, one by one, * showing the contents of the array after each operation * and the corresponding visualisation of the heap. */ System.out.println("Removing items"); while (!h.isEmpty()) { System.out.println(h.remove()); visualiser.show(h); } visualiser.close(); in.close(); } }