A simple calculator using switch statements in java

 import java.util.Scanner;

//import javax.swing.JOptionPane;

class Inputs{

int num1,num2;

int add() {

return num1+num2;

}

int subtract() {

return num1-num2;

}

int multiplication() {

return num1*num2;

}

int division() {

try {

return num1/num2;

}

catch(ArithmeticException e) {

System.out.println("cannot divide by zero");

}

return 0;

}

void setNum(int x,int y) {

num1=x;

num2=y;

}

}

public class Calculator {

public static void main(String[] args) {

Inputs box = new Inputs();

int a,b,c,ans;

Scanner obj1 = new Scanner(System.in);

System.out.println("Enter first number ");

a=obj1.nextInt();

System.out.println("Enter second number ");

b=obj1.nextInt();

box.setNum(a, b);

System.out.println("Choose 1 for addition, 2 for subtraction, 3 for multiplication & 4 for division ");

c=obj1.nextInt();

switch(c) {

case 1:

ans=box.add();

System.out.println("your ans is=" +ans);

break;

case 2: 

ans=box.subtract();

System.out.println("your ans is=" +ans);

break;

case 3: 

ans=box.multiplication();

System.out.println("your ans is=" +ans);

break;

case 4: 

ans=box.division();

System.out.println("your ans is=" +ans);

break;

default:

System.out.println("Illegal input");

}

obj1.close();

}

}

OUTPUT

Enter first number 

45

Enter first number 

10

Choose 1 for addition, 2 for subtraction, 3 for multiplication & 4 for division 

3

your ans is=450


Comments

Popular posts from this blog

Java Program to find average of Three numbers

Java Swing Complete examples step by step(make a project with swing)

A simple method using string to check whether the input password is correct or not