Write a function called mathgame.m that repeatedly asks a user to answer a simpl
ID: 3843770 • Letter: W
Question
Write a function called mathgame.m that repeatedly asks a user to answer a simple addition question. After each question the user is told if their answer is correct or incorrect and they are given the opportunity to continue or to stop. When they stop a summary of their results for the game is provided. Tackle this problem in small pieces. The following is a suggested strategy but certainly not the only one: • Create two random integers between 1 and 10 and store them in separate variables. • Compute the sum of the two integers and store the result in another variable. • Output the question so the user can see the two random numbers but can not see the result of the sum operation. • Prompt the user to enter their guess and collect it using the input function. • Determine if the user’s guess matches the result that you have stored for the sum of the numbers. If they match print out ’correct’. If they don’t print out ’incorrect’. • If the above steps are working, wrap them in a while loop. Make sure you loop condition is initially set to true or your program won’t run. • The last line of your loop should be to ask the user if they want another question. If they enter ’y’ the loop repeats. Anything else and the loop ends. • Finally, use variables to keep track of the number of questions, the number correct and the number incorrect. Display this information as shown in the output below.
Explanation / Answer
ANSWER:
Java program
import java.util.Random;
import java.util.Scanner;
public class MathGame {
public static void main(String[] args) {
int numberOfAttemots = 0;
int correctGuess = 0;
int incorrectGuess = 0;
char flag = 'y';
do {
Random random = new Random();
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
int num1 = random.nextInt(10) + 1;
int num2 = random.nextInt(10) + 1;
int sum = num1 + num2;
numberOfAttemots++;
System.out.println("First Number:"+num1+" Second Number:"+num2);
System.out.print("Enter sum: ");
int guess = scan.nextInt();
if(sum == guess) {
correctGuess++;
System.out.println("Correct...");
}
else
incorrectGuess++;
System.out.print("Do you want to continue (y/n): ");
flag = scan.next().charAt(0);
}while(flag == 'y' || flag == 'Y');
System.out.println("Total number of attempts: "+numberOfAttemots);
System.out.println("Correct: "+correctGuess);
System.out.println("Incorrect: "+incorrectGuess);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.