16. write a program in java using a menu to add, subtract, multiply or divide 2 numbers
Answers
Answer:
Java Program to Calculate the Sum, Multiplication, Division and Subtraction of Two Numbers
public class Calculate.
int m, n, opt, add, sub, mul;
double div;
Scanner s = new Scanner(System.
System. out. print("Enter first number:");
m = s. nextInt();
System. out. print("Enter second number:");
n = s. nextInt();
The given program is solved using switch case.
import java.util.*;
public class MenuDriven{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int a,b,result=0;
System.out.print("Enter first number: ");
a=sc.nextInt();
System.out.print("Enter second number: ");
b=sc.nextInt();
System.out.println("1. Addition.");
System.out.println("2. Subtraction.");
System.out.println("3. Multiplication.");
System.out.println("4. Division.");
System.out.println("5. Modulus.");
System.out.print("\nEnter your choice: ");
switch(sc.nextInt()){
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
case 5:
result=a%b;
break;
default:
System.out.println("Invalid Choice. Program Terminated.");
System.exit(0);
}
System.out.println("Result is: "+result);
}
}
Note: If the user enters an invalid choice, an error message will be shown and the program will be terminated.
See the attachment for output.