INTRODUCTION TO COMPUTER SCIENCE
Robert Sedgewick and Kevin Wayne


This is the syntax highlighted version of Ternary.java.

/*************************************************************************
 *  Compilation:  javac Ternary.java
 *  Execution:    java Ternary
 *
 *  ADT for 3-way logic (true, false, unknown).
 *
 *  Remarks
 *  -------
 *    - use enum when Java 1.5 arrives
 *
 *************************************************************************/

public class Ternary {
    public final static Ternary UNKNOWN = new Ternary();
    public final static Ternary TRUE    = new Ternary();
    public final static Ternary FALSE   = new Ternary();

    // can't instantiate
    private Ternary() { }


    public static Ternary and(Ternary x, Ternary y) {
        if      (x == null    || y == null)    throw new NullPointerException();
        else if (x == FALSE   || y == FALSE)   return FALSE;
        else if (x == UNKNOWN || y == UNKNOWN) return UNKNOWN;
        else                                   return TRUE;
    }

    public static Ternary or(Ternary x, Ternary y) {
        if      (x == null    || y == null)    throw new NullPointerException();
        else if (x == TRUE    || y == TRUE)    return TRUE;
        else if (x == UNKNOWN || y == UNKNOWN) return UNKNOWN;
        else                                   return FALSE;
    }

    public static Ternary not(Ternary x) {
        if      (x == null)    throw new NullPointerException();
        if      (x == TRUE)    return FALSE;
        else if (x == FALSE)   return TRUE;
        else                   return UNKNOWN;
    }

    public String toString() {
        if      (this == TRUE)    return "true   ";
        else if (this == FALSE)   return "false  ";
        else if (this == UNKNOWN) return "unknown";
        else throw new RuntimeException("Illegal value");
    }


    /////////////////////////////////////////////////////////////////////////

    // test client
    public static void main(String[] args) {
        Ternary a = Ternary.TRUE;
        Ternary b = Ternary.not(a);
        Ternary c = Ternary.UNKNOWN;
        Ternary d = Ternary.and(a, c);
        Ternary e = Ternary.or(a, c);
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
        System.out.println(e);

        // null case
        Ternary f = null;
        System.out.println(f);
        Ternary g = Ternary.or(e, f);
        System.out.println(g);
    }
}



Last updated: Mon May 24 12:02:56 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.