/* Marty Stepp, CSE 142, Autumn 2008 Asks the user to do multiplication problems and score them. Example output: 14 * 8 = 112 Correct! 5 * 12 = 60 Correct! 8 * 3 = 24 Correct! 5 * 5 = 25 Correct! 20 * 14 = 280 Correct! 19 * 14 = 256 Incorrect; the answer was 266 You solved 5 correctly Last correct answer was 280 */ import java.util.*; public class MultiplicationTutor { public static void main(String[] args) { Scanner console = new Scanner(System.in); Random rand = new Random(); // fencepost solution - pull first question outside of loop int correct = 0; int last = ask(console, rand); int lastCorrect = 0; // loop until user gets one wrong while (last != 0) { lastCorrect = last; correct++; last = ask(console, rand); } System.out.println("You solved " + correct + " correctly"); if (correct > 0) { System.out.println("Your last correct answer was " + lastCorrect); } } // Asks the user one multiplication problem, // returning true if they get it right and false if not. public static int ask(Scanner console, Random rand) { // pick two random numbers between 1 and 20 inclusive int num1 = rand.nextInt(20) + 1; int num2 = rand.nextInt(20) + 1; System.out.print(num1 + " * " + num2 + " = "); int answer = console.nextInt(); if (answer == num1 * num2) { System.out.println("Correct!"); return answer; } else { System.out.println("Incorrect; the correct answer was " + (num1 * num2)); return 0; } } }