In: Computer Science
Write a program that plays an addition game with the user (imagine the user is a 5th grade student).
First ask the user how many addition problems they want to attempt.
Next, generate two random integers in the range between 10 and 50 inclusive. You must use the Math.random( ) method call. Prompt the user to enter the sum of these two integers. The program then reports "Correct" or "Incorrect" depending upon the user's "answer". If the answer was incorrect, show the user the the correct sum.
Display a running total of how many correct out of how many total problems ( ex: 2 correct out of 5, 3 correct out of 5, etc) after each problem is answered.
Continue this until the user has attempted the total number of problems desired.
java
JAVA PROGRAM:
import java.util.*;
// class Test
class Test {
// main() nethod
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Declare the variable
// Random integers in the range between 10 and 50 inclusive
int low = 10;
int up = 50;
int userAns,correctAns;
int correct = 0;
// Ask the user how many addition problems they want
System.out.print("How many addition problems they want to attempt: ");
int n = sc.nextInt();
// Continue this until the user has attempted the total number of problems desired.
for(int i=0;i<n;i++){
// Generate two random integers num1 and num2
// using Math.random() method call
int num1 = (int)(Math.random() * ((up - low)+1)) + low;
int num2 = (int)(Math.random() * ((up - low)+1)) + low;
// calculate the correct sum
correctAns = num1 + num2;
// display the two random number
System.out.print("Sum is "+num1+" + "+num2+" = ");
// ask the student enter the sum of two number
userAns = sc.nextInt();
// if the user answer is correct
if(userAns==correctAns){
// then display the correct
System.out.println("Correct");
// count the correct answer
correct++;
}else{
// if the user answer is wrong then print the incorrect messgae
System.out.println("Incorrect");
// Display the two random number and their sum
System.out.println("correct is "+num1+" + "+num2+" = "+correctAns);
}
// Display the how many correct out of how many total problems
System.out.println(correct+" correct out of "+n);
System.out.println();
}
}
}
OUTPUT:
NOTE: If you don't understand any step please tell me.