// Helene Martin, CSE 142 // Plays an addition game with the user: prompts them with // addition puzzles with 2 - 5 operands until they get // 3 wrong // goal: demonstrate a systematic process for writing // a medium-size program with a game loop. // we started by getting a single game to work // we put that game in a method // we called that game in a while loop // we noticed we needed information from the method so returned points import java.util.*; public class AdditionGame { public static void main(String[] args) { Random rand = new Random(); Scanner console = new Scanner(System.in); int wrong = 0; int points = 0; while (wrong < 3) { int point = playGame(rand, console); if (point == 0) { wrong++; } else { points++; } } System.out.println("You earned " + points + " points"); } // plays a single addition game with the user. Returns // the number of points earned (1 or 0) public static int playGame(Random rand, Scanner console) { int operands = rand.nextInt(4) + 2; int operand = rand.nextInt(10) + 1; System.out.print(operand); int sum = operand; for (int i = 1; i < operands; i++) { operand = rand.nextInt(10) + 1; System.out.print(" + " + operand); sum += operand; } // great debugging trick: // System.out.print(" = (THE ANSWER IS " + sum + ")"); System.out.print(" = "); int userGuess = console.nextInt(); if (userGuess != sum) { System.out.println("Wrong! The answer was " + sum); return 0; } else { return 1; } } }