I managed to make these two classess, but "score" has to have 7 digits after the dot. I cannot modify Main class. I think I should use String.format("%.7f", ...) but I don't know where. Please help.
MAIN:
public class Main {
public static void main(String[] args) {
Calc c = new Calc();
String score = c.doCalc(args[0]);
System.out.println(score);
}
}
CALC:
public class Calc {
public String doCalc(String cmd) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
return engine.eval(cmd).toString();
}
catch (ScriptException e) {
return "Invalid command to calc";
}
}
}
You can parse the string result back to Double and feed it to String.format:
try {
return String.format("%.7f", Double.valueOf(engine.eval(cmd).toString()));
}
catch (Exception e) {
return "Invalid command to calc";
}
You could of course feed the result directly to String.format without the toString and valueOf round trip, like so:
return String.format("%.7f", engine.eval(cmd));
But that only works when the eval result is a valid floating point number. To deal with other cases like integers or non-numbers, you'd have to put in a few type checks and make the code look more cluttered.