I'm looking for a way to shorten this code up and avoid repeating code and if statements. What I'm doing is creating a calculator that searches strings for operators "* / + - " and executes them accordingly. Any ideas?
if(exp.charAt(i)=='*')
{
newResult=Integer.parseInt(exp.substring(0, i)) * Integer.parseInt(exp.substring(i+1, exp.length()));
primeResult = newResult;
System.out.println(primeResult);
}
else if(exp.charAt(i)=='/')
{
newResult=Integer.parseInt(exp.substring(0, i)) / Integer.parseInt(exp.substring(i+1, exp.length()));
primeResult = newResult;
System.out.println(primeResult);
}
else if(exp.charAt(i)=='+')
{
newResult=Integer.parseInt(exp.substring(0, i)) + Integer.parseInt(exp.substring(i+1, exp.length()));
primeResult = newResult;
System.out.println(primeResult);
}
else if(exp.charAt(i)=='-')
{
newResult=Integer.parseInt(exp.substring(0, i)) - Integer.parseInt(exp.substring(i+1, exp.length()));
primeResult = newResult;
System.out.println(primeResult);
}
Also, is there a solution to accept a string with more than 2 operands? i.e. 5 + 10 * 2 / 3
Here's a snippet:
You could write an
AbstractCalculationOperation
class withexecute
method, withAdd
,Subtract
, etc extending it.Then, just parse
leftHand
,rightHand
, andcalculationOperation
and runcalculationOperation.execute( rightHand, leftHand )
.And then:
Alternate enum variant:
and then:
For changing the code you could use a switch statement and putting some of the redundant code before or after the switch.
It's pretty simple how to avoid too much code repetition:
But to do something more general, robust and useful, with arbitrary nesting levels, you should use some real parser. For example.
Shorten the code by grabbing the variables separately from doing the operation. This will not reduce your "if" statements, but it will drastically reduce the line numbers.
Don't do multiple variables until you understand trees... I've never worked with them personally, but I think "expression trees" are what you'll be after. (note: I just checked on google, yep, Expression Trees)
There's no need of
switch
statements and complex hierrachies of classes.In order to simplify and shorten your code and calculate simple and complex expressions (represented as
String
objects), you can use the Java'sJavaScript API
and it'sScriptEngine
class, which basically simulates aJavaScript
console.This will output:
10.0