Question
Help fixing this porgram in java Add a loop to the program so that the user can determine if they want to try another math
Help fixing this porgram in java
Add a loop to the program so that the user can determine if they want to try another math problem. After the user is informed whether they answered the problem correctly or not, ask the user if they want to try again. Based on their answer, either repeat the code or quit. Also, add a farewell message at the end (after they choose to quit.)
Hints:
You will be adding/inserting code, beyond that, the existing code should not be altered.
The portion of the program that should loop occurs from lines 22 - 45.
The test for the loop will depend on the type of data (String, char, int) you use.
The program:
import javax.swing.JOptionPane; // Needed JOptionPane class
import java.util.Random; // Needed for the Random class
/**
This program demonstrates the Random class.
*/
public class MathTutor
{
public static void main(String[] args)
{
int number1; // A number
int number2; // A second number
int sum; // The sum of the numbers
int userAnswer; // The user's answer
String inputString; // Keyboard input
// Create a Random class object.
Random randomNumbers = new Random();
// Get two random numbers between 1 and 100
number1 = randomNumbers.nextInt(100);
number2 = randomNumbers.nextInt(100);
// Calculate the answer.
sum = number1 + number2;
// Display an addition problem and get the user's answer
inputString = JOptionPane.showInputDialog("What is the answer to
the following problem: " +
number1 + " + " +
number2 + " = ?");
// Convert the user's answer to a number
userAnswer = Integer.parseInt(inputString);
// Display the user's results.
if (userAnswer == sum)
{
JOptionPane.showMessageDialog(null, number1 + " + " + number2
+ " = " +
userAnswer + " Correct!");
}
else
{
JOptionPane.showMessageDialog(null, number1 + " + " + number2
+ " = " +
userAnswer + " Sorry, that
is wrong " +
"The correct answer is " + sum);
}
} //end of main()
} // end of MathTutor
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started