/** @author Scott Marshall @author University of Glasgow, MSc IT Project 2001 @author Building an OnLine Course in Computing Fundamentals */ package ukacgla_BinaryConverter; /** Checker class function is to check student input, and determine if correct or not */ public class Checker{ private ConverterFrame frame; /** Specifies the row in a TableModel holding student answers. */ private int answerRow = 0; public Checker(ConverterFrame f){ frame = f; } /** calcAnswer() calculates the the correct answer. It works by : 1. Getting the number to be calculated from the ConverterFrameObject. 2. Creating a new StringBuffer. 3. Calculating the number using the smart power algorithmn used in the calcPower() method, and building the StringBuffer as the answer. The StringBuffer is then returned as a string for use in comparison. */ protected String calcAnswer() { int power = frame.getPower(); int base = frame.getBase(); int question = frame.getQuestion(); StringBuffer answer = new StringBuffer(); while (power >= 0){ int sum = calcPower(base,power); if (question>= sum){ answer.append("1"); question = question - sum; } else answer.append("0"); power--; } return answer.toString(); } /** verifyAnswer() is used to get the students input, and compare it to the String generated by calcAnswer(). verifyAnswer() checks the specifed line (defined in the answerRow variable) in the studentAnswer table. The method begins checking at Column Index 1 to skip the labels in Column 0. */ protected boolean verifyAnswer(){ boolean answer; StringBuffer studentAnswer = new StringBuffer(); for (int i = 1 ; i < frame.getCols() ; i++) studentAnswer.append(frame.getValue(answerRow,i)); if (studentAnswer.toString().equals(calcAnswer())) answer = true; else answer = false; return answer; } /** Returns b to the power n (providing b is non negative integer). This uses a smart power algorithmn to quickly calculate the maximum value for any number to the power of another number. */ protected int calcPower(int b, int n) { int p = 1; int q = b; int m = n; while (m>0) { if (m%2 !=0) p*=q; m/=2; q*=q; } return p; } }