Guest

Segun

By: a guest on Jul 19th, 2011  |  syntax: Java  |  size: 1.49 KB  |  hits: 216  |  expires: Never
download  |  raw  |  embed  |  report abuse
Copied
  1. import java.util.Random;
  2.  
  3. /**
  4.  *
  5.  * @author trinisoftinc
  6.  */
  7. public class Captcha {
  8.  
  9.     private int q1;
  10.     private int q2;
  11.     private String operation;
  12.     private String[] operations = {
  13.         "+", "-", "*"
  14.     };
  15.  
  16.     public Captcha() {
  17.     }
  18.  
  19.     public String getQuestion() {
  20.         Random r = new Random(System.currentTimeMillis());
  21.  
  22.         int operationRandInt = r.nextInt(3);
  23.         String operationString = operations[operationRandInt];
  24.  
  25.         int q1Rand = r.nextInt(100) + 10;
  26.         int q2Rand = r.nextInt(100) + 10;
  27.  
  28.         //we don't want answers to have -negative results
  29.         if (operationString.equals("-")) {
  30.             while (q2Rand >= q1Rand) {
  31.                 q2Rand = r.nextInt(100) + 10;
  32.             }
  33.         }
  34.  
  35.         /*
  36.             if you want to implement for division, be my guest.
  37.             A few thoughts though.
  38.          * 1. It will be easier if there are no reminders in answers. i.e q1/q2 = Whole Number
  39.          * 2. It will be safer if q1 != q2.
  40.          */
  41.  
  42.         q1 = q1Rand;
  43.         q2 = q2Rand;
  44.         operation = operationString;
  45.  
  46.         return q1 + " " + operation + " " + q2;
  47.     }
  48.  
  49.     public boolean solve(int answer) {
  50.         if (operation.equals("+")) {
  51.             return q1 + q2 == answer;
  52.         } else if (operation.equals("-")) {
  53.             return q1 - q2 == answer;
  54.         } else if (operation.equals("*")) {
  55.             return q1 * q2 == answer;
  56.         }
  57.         return false;
  58.     }
  59. }