In: Computer Science
JAVA PROGRAM
Write program that will prompt user generate two random integers with values from 1 to 10 then subtract the second integer from the first integer. Note, if the second integer is greater than the first integer, swap the two integers before making the subtraction.Then prompt user for the answer after the subtraction. If the answer is correct, display “Correct”otherwise display “Wrong”.You will need to do this in a loop FIVE times and keep a count of how many guesses that were correct and how many that were wrong. Afterthe five subtractions done, display the number of correct and wrong answers.
Explanation:
Here is the code which creates 2 random numbers and then takes the guess for the subtraction from the user.
Then, it happens again and again for new numbers generated everytime and correct and wrong answers are displayed at the end.
Code:
import java.util.Random;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Random r = new Random();
Scanner sc = new
Scanner(System.in);
int correct = 0, wrong = 0;
for(int i=0; i<5; i++)
{
int a = r.nextInt(10) + 1;
int b = r.nextInt(10) + 1;
System.out.println("Random Numbers
generated!");
if(b>a)
{
int temp = a;
a = b;
b = temp;
}
System.out.print("Enter guess for
subtraction: ");
int guess = sc.nextInt();
if(guess == (a-b))
{
System.out.println("Correct");
correct++;
}
else
{
System.out.println("Wrong");
wrong++;
}
}
System.out.println("Correct
answers: "+correct);
System.out.println("Wrong answers:
"+wrong);
}
}
Output:
PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!
PLEASE COMMENT IF YOU NEED ANY HELP!