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 &quo
Here's a snippet:
public static void main(String[] args) {
float primeResult;
String exp = "4-2";
int i = 1;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
char[] myVar = new char[] { '*', '/', '-', '+' };
for (int myVarCtr = 0; myVarCtr < myVar.length; myVarCtr++) {
if (exp.charAt(i) == myVar[myVarCtr]) {
try {
primeResult = Float.parseFloat(engine.eval(
(Integer.parseInt(exp.substring(0, i)))
+ Character.toString(myVar[myVarCtr])
+ (Integer.parseInt(exp.substring(i + 1,
exp.length())))).toString());
System.out.println(primeResult);
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
}