In: Computer Science
Java
Math Tutor:
Write a program that displays a menu as shown in the sample run. You can enter 1, 2, 3, or 4 for choosing an addition, subtraction, multiplication, or division test. After a test is finished, the menu is redisplayed. You may choose another test or enter 5 to exit the system. Each test generates two random single-digit numbers to form a question for addition, subtraction, multiplication, or division. For a subtraction such as number1 – number2, number1 is greater than or equal to number2. For a division question such as number1 / number2, number2 is not zero.
Here is a sample run: (red indicates a user input)
Main menu 1:
Addition 2:
Subtraction 3:
Multiplication 4:
Division 5:
Exit Enter a choice: 1
What is 1 + 7? 8 Correct
Continue? (y/n) y
Enter a choice: 3
What is 2 * 3? 7
Your answer is wrong.
The correct answer is 6.
Continue? (y/n) n
Good bye!
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class allTest {
public static void main (String args[])
{
Scanner sc = new Scanner (System.in);
float res = 0;
int num1,num2,r;
Random randomNumbers = new Random();
System.out.println("Addition 1");
System.out.println("Subtraction 2");
System.out.println("Multiplication 3");
System.out.println("Division 4");
System.out.println("Exit 5");
while(true)
{
//generate random number
num1 = randomNumbers.nextInt(9);
num2 = randomNumbers.nextInt(9);
System.out.println("Enter choice: ");
int ch=sc.nextInt();
switch(ch)
{
case 1:
//addintion of number
System.out.println("What is "+num1+" + "+num2);
res=num1+num2;
r=sc.nextInt();
if(res==r)
{
System.out.println("Correct");
}
else
{
System.out.println("Your answer is wrong.");
System.out.println("The correct answer is
"+res);
}
break;
case 2:
//subtraction ofnumber
if(num1>=num2)
{
System.out.println("What is "+num1+" - "+num2);
res=num1-num2;
}
else
{
System.out.println("What is "+num2+" - "+num1);
res=num2-num1;
}
r=sc.nextInt();
if(res==r)
{
System.out.println("Correct");
}
else
{
System.out.println("Your answer is wrong.");
System.out.println("The correct answer is
"+res);
}
break;
case 3:
System.out.println("What is "+num1+" * "+num2);
res=num1*num2;
r=sc.nextInt();
if(res==r)
{
System.out.println("Correct");
}
else
{
System.out.println("Your answer is wrong.");
System.out.println("The correct answer is
"+res);
}
break;
case 4:
if(num2==0)
{
System.out.println("divisor is zero");
}
else
{
System.out.println("What is "+num1+" / "+num2);
res=num1/num2;
}
r=sc.nextInt();
if(res==r)
{
System.out.println("Correct");
}
else
{
System.out.println("Your answer is wrong.");
System.out.println("The correct answer is
"+res);
}
break;
case 5:
System.out.println("good bye!");
System.exit(1);
default:
System.out.println("Invalid input");
break;
}
System.out.println("Continue? (y/n)");
String c=sc.next();
//check user wants to exit or not
if(c.equals("n") || c.equals("N"))
{
System.out.println("good bye!");
break;
}
}
}
}