CS302 Fall 2012 Exam 2 Solution // Part III: Write an Instantiable Class import java.util.Random; public class ProblemGen { public static final int ADD = 0; public static final int SUB = 1; public static final int MUL = 2; public static final int DIV = 3; private final int MIN; // private final int MAX; // private final int OP; // private int op1, op2; // the operands private String question; // the problem private double answer; // the answer private static Random rng = new Random(); public ProblemGen (int low, int hi, int op) { MIN = low; MAX = hi; OP = op; nextQuestion(); } private void nextQuestion() { op1 = rng.nextInt(MAX-MIN+1)+MIN; // randomly pick each operand op2 = rng.nextInt(MAX-MIN+1)+MIN; // set question and answer fields char c = '?'; answer = 0; if ( OP == ADD ) { c = '+'; answer = op1 + op2; } else if ( OP == SUB ) { c = '-'; answer = op1 - op2; } else if ( OP == MUL ) { c = '*'; answer = op1 * op2; } else if ( OP == DIV ) { c = '/'; answer = op1 / (double)op2; } question = op1 + " " + c + " " + op2 ; } public String getQuestion() { return question; } public String toString() { return question + " = " + answer; } public boolean isCorrect( double possible ) { double err = 0.001; // returns true if possible is close to answer return ( answer-err < possible && possible < answer+err ); }