/* Marty Stepp, CSE 142 Asks the user to do adding problems and scores them. Example output: 4 + 10 + 3 + 10 = 27 9 + 2 = 11 8 + 6 + 7 + 9 = 25 Wrong! The answer was 30 5 + 9 = 13 Wrong! The answer was 14 4 + 9 + 9 = 22 3 + 1 + 7 + 2 = 13 4 + 2 + 10 + 9 + 7 = 42 Wrong! The answer was 32 You earned 4 total points. */ import java.util.*; public class AddingGame { public static void main(String[] args) { Scanner console = new Scanner(System.in); Random rand = new Random(); // stop when they get 3 wrong int wrong = 0; int right = 0; while (wrong < 3) { int score = play(console, rand); if (score == 0) { // user got it wrong wrong++; } else { // user got it right (score == 1) right++; } } System.out.println("You earned " + right + " total points."); } // Plays one addition problem, picking 2-5 random numbers from 1-10. // Returns 1 if the user scored a point (got it right), and 0 if not. public static int play(Scanner console, Random rand) { // pick 2-5 randomly generated numbers int count = rand.nextInt(4) + 2; // 2-5 // handle fencepost problem by grabbing 1st number outside loop int answer = rand.nextInt(10) + 1; System.out.print(answer); // pick the remaining numbers (first one was picked before loop) for (int i = 2; i <= count; i++) { int num = rand.nextInt(10) + 1; answer += num; System.out.print(" + " + num); } System.out.print(" = "); // read user's guess and check whether it is correct int guess = console.nextInt(); if (guess == answer) { return 1; } else { System.out.println("Wrong! The answer was " + answer); return 0; } } }