Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic Calculator program in Java
package com.osfg;
import java.util.Scanner;
/**
*
* @author aniket
*
* Basic Calculator program in Java
*/
public class Calculator {
Scanner scanner;
//boolean to terminate calculator program base on user input
private boolean calculatorStarted;
public Calculator() {
scanner = new Scanner(System.in);
calculatorStarted = true;
}
public void startCalculator() {
boolean invalidInputs = false;
while (calculatorStarted) {
invalidInputs = false;
System.out.println("Enter 1 for addition \n" + "Enter 2 for subtraction \n"
+ "Enter 3 for multiplication \n" + "Enter 4 for division \n" + "Enter 0 for Exit : ");
int operator = scanner.nextInt();
float firstNo = 0;
float secondNo = 0;
if(operator != 0) {
System.out.println("Enter first number : ");
firstNo = scanner.nextFloat();
System.out.println("Enter second number : ");
secondNo = scanner.nextFloat();
}
float result = 0;
switch (operator) {
case 1:
result = add(firstNo, secondNo);
break;
case 2:
result = subtract(firstNo, secondNo);
break;
case 3:
result = multiply(firstNo, secondNo);
break;
case 4:
if(secondNo == 0) {
System.out.println("Please provide proper input \n");
invalidInputs = true;
break;
}
result = divide(firstNo, secondNo);
break;
case 0:
calculatorStarted = false;
System.out.println("Calculator program Terminated \n");
break;
default:
invalidInputs = true;
System.out.println("Please provide proper input \n");
}
/**
* Show the result only if inputs are valid
* and user had not chose to terminate calculator
*/
if(!invalidInputs && operator != 0) {
System.out.println("Result is " + result);
}
}
}
private float add(float number1, float number2) {
return number1 + number2;
}
private float subtract(float number1, float number2) {
return number1 - number2;
}
private float multiply(float number1, float number2) {
return number1 * number2;
}
private float divide(float number1, float number2) {
return number1 / number2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment