// Zorah Fung, CSE 142 // An interactive game that gives the user randomly generated math expressions to solve. // Continues to give user expressions until 3 expressions are answered incorrectly. import java.util.*; public class AdditionGame { public static void main(String[] args) { Scanner console = new Scanner(System.in); Random rand = new Random(); int misses = 0; int points = 0; while (misses < 3) { boolean correct = playGame(console, rand); if (correct) { points++; } else { misses++; } } System.out.println("You earned " + points + " total points"); } // Asks the user to solve a single randomly generated mathematical expression // Uses the given Random to randomly generate the expression. Returns true // if the user answers expression correctly, false otherwise. // Note: We changed the return type from int to boolean since there are only // two possible return values: user got it right or did not public static boolean playGame(Scanner console, Random rand) { int operands = rand.nextInt(4) + 2; int actualSum = 0; for (int i = 1; i <= operands - 1; i++) { int number = rand.nextInt(31); System.out.print(number + " + "); actualSum += number; } int lastNumber = rand.nextInt(31); actualSum += lastNumber; System.out.print(lastNumber + " = "); // Note: Remove debugging code before submitting your solution! // System.out.print("hint: " + actualSum + " "); for debugging. int guess = console.nextInt(); if (actualSum != guess) { System.out.println("Wrong! The answer was " + actualSum); return false; } return true; } }