Program to make a calculator for basic calculations (Addition, Subtraction, Multiplication, Division) of two numbers from user depending upon user choice. Also print an error message if user choice does not match.
Java
import java.util.*;
public class BasicCalculator
{
public static void main(String args[])
{
int choice=0;
double a,b,result=0.0;
Scanner sc=new Scanner(System.in);
System.out.println("0- To exit program");
System.out.println("1- To add two numbers");
System.out.println("2-To subtract two numbers");
System.out.println("3-To multiply two numbers");
System.out.println("4-To divide two numbers");
System.out.print("Enter your choice: ");
choice=sc.nextInt();
switch(choice)
{
case 0:
{
System.out.println("Calculator exited");
System.exit(1);
}
case 1:
{
System.out.print("A: ");
a=sc.nextDouble();
System.out.print("B: ");
b=sc.nextDouble();
result=a+b;
System.out.println("Result: "+result);
break;
}
case 2:
{
System.out.print("A: ");
a=sc.nextDouble();
System.out.print("B: ");
b=sc.nextDouble();
result=a-b;
System.out.println("Result: "+result);
break;
}
case 3:
{
System.out.print("A: ");
a=sc.nextDouble();
System.out.print("B: ");
b=sc.nextDouble();
result=a*b;
System.out.println("Result: "+result);
break;
}
case 4:
{
System.out.print("A: ");
a=sc.nextDouble();
System.out.print("B: ");
b=sc.nextDouble();
result=a/b;
System.out.println("Result: "+result);
break;
}
default:
{
System.out.println("Invalid choice");
}
}
}
}Java