File: Untitled Document 1 Page 1 of 2
import java.util.*;
/**
* Write a description of class Calculator here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Calculator
{
int operand1;//This variable stores the numeric value of the first operand
int operand2;//This variable stores the numeric value of the second operand
char operator;//This variable stores the numeric value of the operator
String expression;
//This function reads the input of the user
void readExpression()
{
Scanner sc = new Scanner(System.in);
//System.out.print("Enter the expression");
expression = sc.nextLine();
}
//This function assings the values of the instance variables from the expression
void parse()
{
int index = 0;
int lastIndex = 0;
expression.trim();
index = expression.indexOf(" ");
operand1 = Integer.parseInt(expression.substring(0 , index));
lastIndex = expression.lastIndexOf(" ");
operand2 = Integer.parseInt(expression.substring(lastIndex+1));
operator = expression.charAt(index+1);
//Depending upon the operator and the operands this function evaluates the
mathematical statement
int evaluate()
{
int finalValue = 0;
switch(operator)
{
default:
System.out.print("The operator is invalid");
case '+':
finalValue = operand1 + operand2;
break;
case '*':
finalValue = operand1 * operand2;
break;
case '/':
finalValue = operand1 / operand2;
break;
case '-':
finalValue = operand1 - operand2;
break;
}
System.out.print(operand1 + " " + operator + " " + operand2 + "=");
return finalValue;
File: Untitled Document 1 Page 2 of 2
//Main compiles the above functions and makes it work like a calculator in which enter
x to break
public static void main (String [] args)
{
Calculator c1 = new Calculator();
Scanner sc = new Scanner(System.in);
char ch = 'a';
while(true)
{
c1.readExpression();
c1.expression.trim();
if(c1.expression.charAt(0) == 'x')
break;
else
{
if(Character.isDigit(c1.expression.charAt(0)) == true)
{
c1.parse();
}
else
{
c1.operand1 = c1.evaluate();
c1.operator = c1.expression.charAt(0);
c1.operand2 = Integer.parseInt(c1.expression.substring(2));
}
System.out.print( "\f" + c1.evaluate());
}
}
}
}
/**
* Output:
* 11 + 12=23
*
*/