// BitQuiz.java // David Kosbie, 15-111/AB, Spring 2007 /* Standard disclaimer: As usual with sample code designed (often in class!) to demonstrate specific issues, the style may not be perfect (it is especially lacking comments and top-down design), and there may even be a bug or two lurking in the code! */ import java.util.*; public class BitQuiz { private static Scanner scanner = new Scanner(System.in); private static Random random = new Random(); public static int eval(int arg1, String operator, int arg2) { if (operator.equals("&")) return (arg1 & arg2); if (operator.equals("|")) return (arg1 | arg2); if (operator.equals("^")) return (arg1 ^ arg2); if (operator.equals("~")) return (~arg1); if (operator.equals("<<")) return (arg1 << arg2); if (operator.equals(">>")) return (arg1 >> arg2); if (operator.equals(">>>")) return (arg1 >>> arg2); System.out.printf("Unknown operator: %s\n",operator); return 0; } public static void main(String[] args) { System.out.println("This program repeatedly generates random"); System.out.println("bit manipulation problems. Enter a"); System.out.println("non-int value to quit the program.\n"); String[] operators = { "&", "|", "^", "~", ">>", ">>>", "<<" }; // This generates problems in the range [min,max]. Change these // values to make the poblems easier or harder int min = -8, max = 8; while (true) { String operator = operators[random.nextInt(operators.length)]; int arg1 = min + (random.nextInt(max - min + 1)); int arg2; if (operator.length() > 1) // it's a shift operator, so keep arg2 small + non-negative arg2 = random.nextInt(4); else arg2 = min + (random.nextInt(max - min + 1)); if (operator.equals("~")) // unary negation has no second arg! System.out.printf("~%d = ",arg1); else System.out.printf("%d %s %d = ",arg1,operator,arg2); if (!scanner.hasNextInt()) { System.out.println("Goodbye!"); break; } int response = scanner.nextInt(); int result = (byte)eval(arg1,operator,arg2); if (response == result) System.out.println("Correct!!!\n"); else System.out.printf("Sorry, but the answer is: %d\n\n", result); } } }