19. write a program in java using a menu using parameter without return to add,subtract,multiply and divide two numbers
Answers
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.