/** * A class to represent the elements of the language (tokens): integer and symbols. * * @author Marcel Turcotte */ class Token { // constants private static final int INTEGER = 1; private static final int SYMBOL = 2; // instance variables private int iValue; private String sValue; private int type; /** * Creates a token that represents an integer value. */ Token( int iValue ) { this.iValue = iValue; type = INTEGER; } /** * Creates a token that represents a symbol. */ Token( String sValue ) { this.sValue = sValue; type = SYMBOL; } /** * Returns the integer value that is stored in this token; this * method is only applicable if this token isInteger. * * @return The int value stored in this token. */ public int iValue() { // pre-condition if (type != INTEGER) throw new IllegalStateException("not an integer"); return iValue; } /** * Returns the symbol (a String) that is stored in this token; * this method is only applicable if this token isSymbol. * * @return The symbol stored in this token. */ public String sValue() { // pre-condition if (type != SYMBOL) throw new IllegalStateException("not a symbol"); return sValue; } /** * Returns true if this token represents an integer value. * * @return true if this token is a integer. */ public boolean isInteger() { return type == INTEGER; } /** * Returns true if this token represents a symbol. * * @return true if this token is a symbol. */ public boolean isSymbol() { return type == SYMBOL; } /** * Returns a String representation of this token. * * @return A String representation of this token. */ public String toString() { String result; switch (type) { case INTEGER: return Integer.toString(iValue); case SYMBOL: return sValue; default: throw new IllegalStateException("this statement should never be executed"); } } }