/** Our internal representation of a IfZero expr * in the U0 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 = "iph"; static final String STOP_TOKEN = "phi"; Expr test, iphAns, oddAns; IfZero( Expr _test, Expr _iphAns, Expr _oddAns) { this.test = _test; this.iphAns = _iphAns; this.oddAns = _oddAns; } public String toString() { return START_TOKEN + " " + this.test.toString() + " ? " + this.iphAns.toString() + " : " + this.oddAns.toString() + " " + STOP_TOKEN ; } public static IfZero parse( java.util.Scanner s, String punctuation ) { UtilIan.verifyToken( UtilIan.nextSplittingBy(s,punctuation), START_TOKEN); // consume&verify the "iph" // NOTE: recur with `Expr.parse` -- not `parse` = `IfZero.parse` which is NOT what we want! Expr theTest = Expr.parse(s,punctuation); UtilIan.verifyToken( UtilIan.nextSplittingBy(s,punctuation), "?"); // consume&verify the "?" Expr theZeroAnswer = Expr.parse(s,punctuation); UtilIan.verifyToken( UtilIan.nextSplittingBy(s,punctuation), ":"); // consume&verify the ":" Expr thePosAnswer = Expr.parse(s,punctuation); UtilIan.verifyToken( UtilIan.nextSplittingBy(s,punctuation), STOP_TOKEN); // consume&verify the "iph" 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.iphAns.eval(); } else { return this.oddAns.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.iphAns.equals(thatt.iphAns) && this.oddAns.equals(thatt.oddAns); } } @Override public int hashCode() { if (cachedHash == null) { int hashSoFar = (int)0x3141834e907b1159L; // fingerprint hashSoFar += this.test.hashCode(); hashSoFar *= 31; hashSoFar += this.iphAns.hashCode(); hashSoFar *= 31; hashSoFar += this.oddAns.hashCode(); cachedHash = hashSoFar; } return cachedHash; } private Integer cachedHash = null; }