Hello everyone I need to create a Calculator program that ne
Hello everyone, I need to create a Calculator program that needs to be written in Java. Here are the details:
Implement the following classes: Calculator, InvalidExpressionException, and Main.
InvalidExpressionException class has a constructor that takes String message and Exception e. This constructor calls super(message, e).
Here is the code for InvalidExpressionException class:
public class InvalidExpressionException extends Exception {
public InvalidExpressionException(String message, Exception e){
super(message,e);
}
}
The Calculator class contains one static method: public static double eval(String expr) throws InvalidExpressionException which will only deal with positive real numbers. It will handle only two number expressions(5 + 78). It performs only addition and subtraction operations. All the code must be in try block. Find the first index of any of the above operators. Take two operands and convert them to doubles using “Double.parseDouble()”. Catch exception must throw an error message.
The Main class has a main() method. All the code in main() must be in a try block. Prompt the user to enter an expression. Read in line as expression. Use Calculator.eval() to get the answer and then print the answer. Catch exception must throw an error message.
Solution
public class Calculator {
public static double eval(String expression) throws InvalidExpressionException
{
try
{
char operator = getOperator(expression);
double operand1 = Double.parseDouble(expression.substring(0, expression.indexOf(operator)));
double operand2 = Double.parseDouble(expression.substring(expression.indexOf(operator), expression.length()));
if(operator == \'+\')
{
return operand1 + operand2;
}
else if(operator == \'-\')
{
return operand1 - operand2;
}
else
{
throw new InvalidExpressionException(\"Invalid expression\", null);
}
}
catch(NullPointerException npe)
{
throw new InvalidExpressionException(\"Two operands are required to evaluate expression\", npe);
}
catch(NumberFormatException nfe)
{
throw new InvalidExpressionException(\"Operand is not valid\", nfe);
}
}
public static char getOperator(String expression) throws InvalidExpressionException
{
if(expression.indexOf(\'+\') > 0)
return \'+\';
else if(expression.indexOf(\'-\') > 0)
return \'-\';
else
throw new InvalidExpressionException(\"Invalid operator\", null);
}
}
public class Main {
public static void main(String args[])
{
try
{
Calculator.eval(\"5+8\");
Calculator.eval(\"5--8\");
}
catch(InvalidExpressionException ife)
{
System.out.println(ife.getMessage());
}
}
}


