Write a program that will call 2 methods in main: addition() and summary(). Defi
ID: 3725627 • Letter: W
Question
Write a program that will call 2 methods in main: addition() and summary(). Define 2 global variables: loopCount and totalWrong, and initialize both to 0.
Task #2:
In the addition() method, define the following local variables:
Random myRan = new Random();
int userAnswer, ranNum1, ranNum2, correctAnswer.
Ask the user how many times they want to practice their addition, and store that in the global variable called loopCount. Create a loop that will repeat loopCount number of times.
Inside the loop, generate 2 random numbers between 1 and 10, and store them in ranNum1 and ranNum2. Ask the user “what is x plus y” where x is ranNum1 and y is ranNum2. Store the user’s answer in userAnswer.
Store the sum of ranNum1 and ranNum2 in the variable called correctAnswer.
Compare the userAnswer with the correctAnswer. If the user got it right, say “correct!” to the user, otherwise say “wrong”. Increment the global variable called totalWrong by 1 for each wrong answer.
Task #3:
In the summary() method, print the following messages:
“There were x number of addition problems generated.”
(where x is the loopCount).
“The total number of problems answered wrong were y.”
(where y is the totalWrong).
“The percentage wrong is z %.”
(where z is the division of totalWrong by loopCount plus 100).
Hint: Be careful about integer division.
Explanation / Answer
import java.util.Random;
import java.util.Scanner;
class Main {
// global variables
static int loopCount;
static int totalWrong;
// method
public static void addition()
{
// declaring varaibles
int userAnswer, ranNum1, ranNum2, correctAnswer;
Random myRan = new Random();
// taking user input
System.out.print("How many times you want to practice your addition? ");
Scanner sc = new Scanner(System.in);
loopCount = sc.nextInt();
// performing test for loopCount times
for(int i=0; i<loopCount; i++)
{
ranNum1 = myRan.nextInt(10) + 1;
ranNum2 = myRan.nextInt(10) + 1;
System.out.printf(" What is %d + %d ? ",ranNum1, ranNum2);
userAnswer = sc.nextInt();
// checking if user answered correctly
if(ranNum1 + ranNum2 == userAnswer)
{
System.out.println("Correct!");
}
else
{
System.out.println("Wrong!");
totalWrong++;
}
}
}
public static void main(String[] args) {
addition();
}
}
/*SAMPEL OUTPUT
How many times you want to practice your addition? 3
What is 1 + 7 ? 2
Wrong!
What is 1 + 1 ? 2
Correct!
What is 2 + 6 ? 8
Correct!
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.