
Segun
By: a guest on Jul 19th, 2011 | syntax:
Java | size: 1.49 KB | hits: 216 | expires: Never
import java.util.Random;
/**
*
* @author trinisoftinc
*/
public class Captcha {
private int q1;
private int q2;
private String operation;
private String[] operations = {
"+", "-", "*"
};
public Captcha() {
}
public String getQuestion() {
Random r = new Random(System.currentTimeMillis());
int operationRandInt = r.nextInt(3);
String operationString = operations[operationRandInt];
int q1Rand = r.nextInt(100) + 10;
int q2Rand = r.nextInt(100) + 10;
//we don't want answers to have -negative results
if (operationString.equals("-")) {
while (q2Rand >= q1Rand) {
q2Rand = r.nextInt(100) + 10;
}
}
/*
if you want to implement for division, be my guest.
A few thoughts though.
* 1. It will be easier if there are no reminders in answers. i.e q1/q2 = Whole Number
* 2. It will be safer if q1 != q2.
*/
q1 = q1Rand;
q2 = q2Rand;
operation = operationString;
return q1 + " " + operation + " " + q2;
}
public boolean solve(int answer) {
if (operation.equals("+")) {
return q1 + q2 == answer;
} else if (operation.equals("-")) {
return q1 - q2 == answer;
} else if (operation.equals("*")) {
return q1 * q2 == answer;
}
return false;
}
}