13 Feb 2012 [ 185 week6 ]

We're going to go over how to use the NetBeans debugger, with an emphasis on helping us understand programs (rather than actually finding bugs).

Exercises

Take a look at the following example that prints prime numbers. Run it in the debugger, stepping through, and paying special attention to scope, values of local variables, and method usage.

import java.util.Arrays;

class Primes {
    public static final int MAX = 50;

    public static void printTrue(boolean flag[]) {
        for (int i = 0; i < flag.length; i++) {
            if (flag[i]) 
                System.out.println(i);
        }
    }

    public static void crossOffMultiples(boolean flag[], int p) {
        for (int mult = 2 * p; mult < flag.length; mult += p)
            flag[mult] = false;
    }

    public static void main(String args[]) {
        // Array to track whether a given number is prime.
        boolean isPrime[] = new boolean[MAX + 1];

        // Initialize all entries (2 and above) to true.
        Arrays.fill(isPrime, true);
        isPrime[0] = false;
        isPrime[1] = false;

        // Cross off multiples of each prime found.
        for (int test = 2; test < isPrime.length; test++) {
            if (isPrime[test])
                crossOffMultiples(isPrime, test);
        }

        // Print everything that hasn't been crossed off.
        printTrue(isPrime);
    }
}

For a more complex example, look at the processing-example project (available in this zip).

Readings