Java programming using Methods This time write a class that contains the four me
ID: 3821869 • Letter: J
Question
Java programming using Methods
This time write a class that contains the four methods:
(Add, Subtract, Multiply, and Divide)
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 re-displayed. 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.
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
class myArithmetic
{
public static void main (String[] args) throws java.lang.Exception
{
int ch;
System.out.print("Choose desired operation ");
System.out.print("Enter 1 for Addition ");
System.out.print("Enter 2 for Subtraction ");
System.out.print("Enter 3 for Multiplication ");
System.out.print("Enter 4 for Division ");
System.out.print("Enter 5 to Exit ");
Scanner scan = new Scanner(System.in);
ch = scan.nextInt();
if(ch == 1)
arithAdd();
if(ch == 2)
arithSub();
if(ch == 3)
arithMul();
if(ch == 4)
arithDiv();
if(ch == 5)
System.exit(0);
}
public static void arithAdd()
{
Random rand = new Random();
int a = rand.nextInt(9) + 0;
int b = rand.nextInt(9) + 0;
int c = a + b;
System.out.print("Sum of 2 random numbers " + a + " and" + b + " is " + c);
}
public static void arithSub()
{
Random rand = new Random();
int a = rand.nextInt(9) + 0;
int b = rand.nextInt(9) + 0;
int c, t;
if(a<b)
{
t = a;
a = b;
b = t;
}
c = a - b;
System.out.print("Subtraction of 2 random numbers " + a + " and" + b + " is " + c);
}
public static void arithMul()
{
Random rand = new Random();
int a = rand.nextInt(9) + 0;
int b = rand.nextInt(9) + 0;
int c = a * b;
System.out.print("Multiplication of 2 random numbers " + a + " and" + b + " is " + c);
}
public static void arithDiv()
{
Random rand = new Random();
int a = rand.nextInt(9) + 0;
int b = rand.nextInt(9) + 1;
int c = a / b;
System.out.print("Division of 2 random numbers " + a + " and" + b + " is " + c);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.