Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

TheMathGame: Your task is to develop a program that will teach youngsters the ba

ID: 3813581 • Letter: T

Question

TheMathGame: Your task is to develop a program that will teach youngsters the basic math facts of addition, subtraction, multiplication and division. The program generates random math problems for students to answer. Players get a small reward for correct answers and suffer a small penalty for incorrect ones. User statistics need to be recorded in a text file so that they me loaded back into the program when the player returns to play the game again. In addition, the youngster should be allowed to see how (s)he is doing at any time while (s)he is playing the game.   

WARNING: Note that your main() function should consist of mostly function calls and not be greater than 100 lines in total; however, your entire program will be closer to 500 - 800 lines of code!

PROGRAM REQUIREMENTS 1. Generate simple math fact problems: a. Addition (the total must be an integer >= 0) b. Subtraction (the difference must be an integer >= 0) c. Multiplication (the product must be an integer >= 0) d. Division (the quotient must be an integer >= 0) 2. Validate user input at every opportunity. If your program crashes because you allow the user to make an invalid entry and you did not write code to handle such potential exceptions, you will NOT pass the midterm! 3. The program should keep track of the following statistics: a. The user’s name b. The total correct answers c. The total wrong answers d. The total earnings ($0.05 is awarded for every correct response and $0.03 is subtracted from every incorrect response) 4. A separate text file must be created for every user: a. Statistics are read from the file at the start of the game (if the user is a returning player). b. Statistics are recorded at the end of every game.
5. The program must be developed using functions so that the main() function consists mostly of function calls. Below is a list of most of the required functions, you may add your own functions if you like: a. credits //This function is used to display your name and what the program does b. menu // This function is used to display the menu with various options
c. validateUserResponse // This function is used to validate user input from the menu d. validateUserAnswer // This function is used to validate user input and ensure that ONLY numeric answers are entered by the user. e. checkUserAnswer // given a math problem, this function is used to check if the answer the user entered is correct or incorrect f. updateStats // This function is used to keep a running total of game statistics (in RAM) g. displayStats // This function is used to display statistics on screen h. retireveStats // This function is used to retrieve player statistics from external txt file when the game starts, assuming the player is a returning player, else create a text file to store the stats. i. saveStats // This function is used to save player statistics on an external txt file. j. You may also want to consider the following four functions: generateAddition, generateSubtraction, generateMultiplication and generateDivision // use these to generate a problem of the appropriate type. 6. You must use meaningful variable names. 7. You must comment your code. 8. You must use variables of the correct type and initialize them with a proper value.

GENERAL RESTRICTIONS :
1. No infinite loops, examples include: a. for(;;) b. while(1) c. while(true) d. do{//code}while(1); 2. No break statements to exit loops

Explanation / Answer

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class MathGame {

   // Max limit for question generation
   private static final int MAX_LIMIT = 10000;
   private static Scanner sc = new Scanner(System.in);
   private static String userName;
   private static int correctAnswers;
   private static int wrongAnswers;

   public static void main(String[] args) {

       // Obtain details from file
       retireveStats();
       boolean exit = false;
       while (!exit) {
           // display menu
           String input = menu();
           // Validate user option
           if (!validateUserResponse(input))
               continue;
           int menuOpt = Integer.parseInt(input);
           // Select operation based on menu option
           switch (menuOpt) {
           case 1:
               startGame();
               break;
           case 2:
               displayStats();
               break;
           case 3:
               credits();
               break;
           case 4:
               saveStats();
               exit = true;
               break;

           }

       }

   }

   private static void saveStats() {
       // Save details to file
       File file = new File(userName);
       try {
           BufferedWriter br = new BufferedWriter(new FileWriter(file));
           br.write(correctAnswers);
           br.write(wrongAnswers);
           br.close();
       } catch (IOException e) {
           e.printStackTrace();
       }

   }

   private static void displayStats() {
       // display statistics
       System.out.println(userName);
       System.out.println("Number of correct answers: " + correctAnswers);
       System.out.println("Number of wrong anwers: " + wrongAnswers);
       System.out.println("Earnings: "
               + String.format("$ %.2f",
                       (correctAnswers * 0.05 - wrongAnswers * 0.03)));

   }

   private static void startGame() {
       Random rand = new Random();
       // random selection of question type
       int type = rand.nextInt(4);
       int answer = 0;
       switch (type) {
       case 0:
           answer = generateAddition();
           break;
       case 1:
           answer = generateSubtraction();
           break;
       case 2:
           answer = generateMultiplication();
           break;
       case 3:
           answer = generateDivision();
           break;
       }
       // accept user input
       String input = sc.next();
       // validate input
       if (validateUserAnswer(input)) {
           // update statistics after checking the answer
           updateStats(checkUserAnswer(Integer.parseInt(input), answer));
       }

   }

   private static void updateStats(boolean correct) {
       // update statistics
       if (correct) {
           correctAnswers++;
       } else {
           wrongAnswers++;
       }

   }

   private static boolean checkUserAnswer(int input, int answer) {
       // Check anwer
       if (input == answer) {
           System.out.println("Correct Answer!!");
           return true;
       } else {
           System.out.println("Wrong Answer!!");
           return false;
       }
   }

   private static boolean validateUserAnswer(String input) {
       // Validate if input is integer
       try {
           Integer.parseInt(input);
           return true;
       } catch (Exception e) {
           return false;
       }
   }

   private static int generateAddition() {
       // generate addition question
       Random rand = new Random();
       int first = rand.nextInt(MAX_LIMIT);
       int second = rand.nextInt(MAX_LIMIT);
       System.out.println(first + " + " + second);
       // return correct answer
       return first + second;
   }

   private static int generateSubtraction() {
       // generate substraction question
       Random rand = new Random();
       int first = rand.nextInt(MAX_LIMIT);
       int second = rand.nextInt(MAX_LIMIT);
       if (first < second) {
           // ensure that answer is positive
           int temp = first;
           first = second;
           second = temp;
       }
       System.out.println(first + " - " + second);
       // return correct answer
       return first - second;
   }

   private static int generateMultiplication() {
       // generate multiplication question
       Random rand = new Random();
       int first = rand.nextInt(MAX_LIMIT);
       int second = rand.nextInt(MAX_LIMIT);
       System.out.println(first + " * " + second);
       // return correct answer
       return first * second;
   }

   private static int generateDivision() {
       // generate division question
       Random rand = new Random();
       int first = rand.nextInt(MAX_LIMIT);
       // avoid division by zero
       int second = rand.nextInt(MAX_LIMIT - 1) + 1;
       System.out.println(first * second + " / " + second);
       // return correct answer
       return first;
   }

   private static boolean validateUserResponse(String input) {
       // validate user menu option
       try {
           // check if integer
           int option = Integer.parseInt(input);
           // check if within range
           if (option >= 1 && option <= 4)
               return true;
           System.out.println("Invalid Option");
           return false;
       } catch (Exception e) {
           System.out.println("Invalid Option");
           return false;
       }
   }

   private static String menu() {
       // display menu
       System.out.println("Menu");
       System.out.println("1. Start");
       System.out.println("2. Statistics");
       System.out.println("3. Credits");
       System.out.println("4. Exit");
       // accept option
       return (sc.next());
   }

   private static void credits() {
       // display credits
       System.out.println("Creator: <Programmer Name>");
       System.out
               .println("The program generates random math problems for students to answer. You will win $0.05 for each"
                       + " correct answer and lose $0.03 for each wrong answer.");
   }

   public static void retireveStats() {
       System.out.println("Enter Username");
       // accept user name
       userName = sc.next();
       File file = new File(userName);
       // check if statistics are present
       if (file.exists()) {

           try {
               // read from file
               BufferedReader bf = new BufferedReader(new FileReader(file));
               correctAnswers = bf.read();
               wrongAnswers = bf.read();
               bf.close();
           } catch (FileNotFoundException e) {
               e.printStackTrace();
           } catch (NumberFormatException e) {
               e.printStackTrace();
           } catch (IOException e) {
               e.printStackTrace();
           }

       } else {
           // set values to zero if statistics are not available
           correctAnswers = 0;
           wrongAnswers = 0;
       }
   }
}