Simple Calculator in java
In this page, we will learn to build a simple calculator application in java
Step 1 : Create interface Calculation.java
package com.javatrainingschool.service;
public interface Calculation {
public int addNumbers(int num1, int num2);
public int subtractNumbers(int num1, int num2);
public int multiplyNumbers(int num1, int num2);
public int divideNumbers(int num1, int num2) throws ArithmeticException;
}
Step 2 : Create implementation class
package com.javatrainingschool.service;
import java.util.List;
public class CalculationImpl implements Calculation {
@Override
public int addNumbers(int num1, int num2) {
return num1 + num2;
}
@Override
public int subtractNumbers(int num1, int num2) {
return num1 - num2;
}
@Override
public int multiplyNumbers(int num1, int num2) {
return num1 * num2;
}
@Override
public int divideNumbers(int num1, int num2) throws ArithmeticException{
return num1 / num2;
}
}
Step 3 : Create the main class
package com.javatrainingschool.service;
import java.util.Scanner;
public class CalculationMainClass {
private static Calculation calculation = new CalculationImpl();
public static void main(String[] args) {
System.out.println("Welcome to Java Calculator Application");
System.out.println("Choose which operation you want to perform");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("Enter the operation Number : ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("Enter the num1 : ");
int num1 = sc.nextInt();
System.out.println("Enter the num2 : ");
int num2 = sc.nextInt();
int result = processInput(input, num1, num2);
System.out.println("The result of the operation is : " + result);
sc.close();
}
public static int processInput(String input, int num1, int num2) {
int result = 0;
switch(input){
case "1" :
result = calculation.addNumbers(num1, num2);
break;
case "2" :
result = calculation.subtractNumbers(num1, num2);
break;
case "3" :
result = calculation.multiplyNumbers(num1, num2);
break;
case "4" :
result = calculation.divideNumbers(num1, num2);
}
return result;
}
}
Output :
Welcome to Java Calculator Application
Choose which operation you want to perform
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter the operation Number :
3
Enter the num1 :
34
Enter the num2 :
5
The result of the operation is : 170