/** Our internal representation of a IfZero expr * in the V0 language. * See http://www.radford.edu/itec380/2019spring-ibarland/Project * * @author Ian Barland * @version 2018.Nov.16 */ public class IfZero extends Expr { static final String START_TOKEN = "?0"; static final String STOP_TOKEN = ":!"; Expr test, zerAns, posAns; IfZero( Expr _test, Expr _zerAns, Expr _posAns) { this.test = _test; this.zerAns = _zerAns; this.posAns = _posAns; } public String toString() { return START_TOKEN + " " + this.test.toString() + " " + this.zerAns.toString() + " " + this.posAns.toString() + " " + STOP_TOKEN ; } public static IfZero parse( java.util.Scanner s, String punctuation ) { UtilIan.verifyToken( UtilIan.nextSplittingBy(s,punctuation), START_TOKEN.substring(0,1)); // consume&verify the '?' of "?0" UtilIan.verifyToken( UtilIan.nextSplittingBy(s,punctuation), START_TOKEN.substring(1) ); // consume&verify the '0' of "?0" // NOTE: recur with `Expr.parse` -- not `parse` = `IfZero.parse` which is NOT what we want! Expr theTest = Expr.parse(s,punctuation); Expr theZeroAnswer = Expr.parse(s,punctuation); Expr thePosAnswer = Expr.parse(s,punctuation); UtilIan.verifyToken( UtilIan.nextSplittingBy(s,punctuation), STOP_TOKEN.substring(0,1)); // consume&verify the ":" of ":!" UtilIan.verifyToken( UtilIan.nextSplittingBy(s,punctuation), STOP_TOKEN.substring(1)); // consume&verify the "!" of ":!" return new IfZero(theTest,theZeroAnswer,thePosAnswer); } static final double EPSILON = 1e-10; public Value eval() { if ( Math.abs((((Num)(this.test.eval())).doubleValue()) % 2) < EPSILON ) { return this.zerAns.eval(); } else { return this.posAns.eval(); } } @Override public boolean equals( /* IfZero this, */ Object that) { if (this==that) { return true; } else if (that==null) { return false; } else if (this.getClass() != that.getClass()) { return false; } else { IfZero thatt = (IfZero) that; return this.test.equals(thatt.test) && this.zerAns.equals(thatt.zerAns) && this.posAns.equals(thatt.posAns); } } @Override public int hashCode() { if (cachedHash == null) { int hashSoFar = 0; hashSoFar += this.test.hashCode(); hashSoFar *= 31; hashSoFar += this.zerAns.hashCode(); hashSoFar *= 31; hashSoFar += this.posAns.hashCode(); cachedHash = hashSoFar; } return cachedHash; } private Integer cachedHash = null; }