Design a program that gives simple math quizzes. The program should display two random numbers that are to be added, such as

247

+ 129

The program (Java language) should allow the student to enter the answer. If the answer is correct, a message of congratulations should be displayed. If the answer is incorrect, a message showing the correct answer should be displayed

Here is the pseudo-code to follow

//Declare the variables to hold intermediate and final values

Declare Integer rand1, rand2, sum ans

//Get the random numbers generated by the function

//random and assign those values in rand1 and rand2 respectively

Set rand1 = random(1, 999)

Set rand2 = random(1, 999)

//Dsiplay rand1 and rand2 in a formatted way treated for addition

Display

Respuesta :

Answer:

  1. import java.util.Scanner;
  2. import java.util.Random;
  3. public class Main {
  4.    public static void main(String[] args) {
  5.        int rand1, rand2, sum, ans;
  6.        Random rand = new Random();
  7.        rand1 = rand.nextInt(1000);
  8.        rand2 = rand.nextInt(1000);
  9.        sum = rand1 + rand2;
  10.        System.out.println(rand1 + " + " + rand2);
  11.         Scanner input = new Scanner(System.in);
  12.        System.out.print("Please enter your answer: ");
  13.        ans = input.nextInt();
  14.        if(ans == sum){
  15.            System.out.println("Congratulations! You did it right!");
  16.        }else{
  17.            System.out.println("Wrong answer. The correct answer should be " + sum);
  18.        }
  19.    }
  20. }

Explanation:

Firstly import Scanner and Random libraries which will be used to get input number and to generate random value (Line 1 -2).

Next declare all the necessary variables as given in pseudo-code (Line 7 - 8)

Then use nextInt method to randomly generate integer and assign them to rand1 and rand 2, respectively (Line 10 - 11). Next, sum up the two random values and assign it to variable ans (Line 12).

Display the two random numbers (Line 14) and create a Scanner object and prompt user input for answer (Line 16- 18).

Create an if-else condition to check if the input answer (ans) is equal to the real answer (sum) and display the appropriate message accordingly (Line 20 - 24).