93.2k views
1 vote
Java Programming: Loops and Conditionals

Laura Brown teaches 3rd grade. She and her students would like a computer program to practice multiplication. Laura would like the students to practice on random multiplication questions based on random numbers between 1 and 10. Laura would also like the student to be able to pick the number of questions that the program will ask.

1 Answer

4 votes

Answer:

  1. import java.util.Scanner;
  2. import java.util.Random;
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner input = new Scanner(System.in);
  6. Random rand = new Random();
  7. System.out.print("Enter number of questions you wish to practice: ");
  8. int n = input.nextInt();
  9. int i = 1;
  10. while(i <= n){
  11. int num1 = 1 + rand.nextInt(10);
  12. int num2 = 1 + rand.nextInt(10);
  13. int answer = num1 * num2;
  14. System.out.print("Question " + i + ": " + num1 + " x " + num2 + " = ");
  15. int response = input.nextInt();
  16. if(response == answer){
  17. System.out.println("Correct answer!");
  18. }
  19. else{
  20. System.out.println("Wrong answer. It should be " + answer);
  21. }
  22. i++;
  23. }
  24. }
  25. }

Step-by-step explanation:

Firstly, we import Scanner and Random classes (Line 1-2) as we need to get user input for number of questions and generate random number in each question.

Next, create a Scanner and Random object (Line 7-8). Prompt user to input number of question and get the input using the Scanner object (Line 10-11).

Next create a while loop and set the condition to loop for n number of times (based on number of questions) (Line 14). In the loop, use Random object nextInt method to generate two integers between 1 -10 (Line 15-16). Prompt user to input an answer using the Scanner object (Line 18-19). If the response is matched with answer print a correct message (Line 21-22) other wise inform user they write a wrong answer and show the correct answer (Line 24-25).

User Lee Warner
by
4.0k points