In: Computer Science
This problem will give you hands-on practice with the following programming concepts: • All programming structures (Sequential, Decision, and Repetition) • Methods • Random Number Generation (RNG) Create a Java program that teaches people how to multiply single-digit numbers. Your program will generate two random single-digit numbers and wrap them into a multiplication question. The program will provide random feedback messages. The random questions keep generated until the user exits the program by typing (-1). For this problem, multiple methods must be used. You can’t put all the code in one method. For example, you can create a void method to generate a random message for correct answers and another method to generate a message for incorrect answers. You can also create a method to generate the random questions, etc. Name your class as Q4Multiplication.java The sample run below shows you the behavior of this program:
For this question, I see an answer already posted on site but when I was studying it, I found out that the question says use multiple methods, Everything in the posted answer is crammed into the main method and so how do I break it into multiple methods??
Following is the program for the same in JAVA
import java.util.Random;
import java.util.Scanner;
public class Q4Multiplication {
public static int randomNumber() {
Random rand = new Random();
int n = rand.nextInt(9) + 1;
return n;
}
// Matching whether the solution matches with
input
public static void matchAnswerWithSolution(int
userInput, int solution) {
if(userInput == solution) {
System.out.println("Correct answer");
}else {
System.out.println("Incorrect answer" + "\nCorrect answer is: " +
(solution));
}
}
// Taking the input
public static int scanInt() {
Scanner scan = new
Scanner(System.in);
return scan.nextInt();
}
// Printing the question by getting the random
numbers
// and returning the solution of multiplication from
the function
public static int printQuestion() {
int randomNumber1 =
randomNumber();
int randomNumber2 =
randomNumber();
System.out.println("Enter the
multiplication of: " + randomNumber1 + " and " +
randomNumber2);
return
randomNumber1*randomNumber2;
}
// Main function
public static void main(String args[]) {
boolean enter = true;
while(enter) {
int solution =
printQuestion();
int userInput =
scanInt();
if(userInput ==
-1) {
enter = false;
break;
}else {
matchAnswerWithSolution(userInput,
solution);
}
}
}
}
Following is the snippet of the output.
That was a nice
question to answer
Friend, If you have any doubts in understanding do let me know in
the comment section. I will be happy to help you further.
Thanks