This JavaScript is saved in the file "risk.js" -
if (age < 25) {
riskFactor = 1.5;
} else if (nbrClaims < 3) {
riskFactor = 0.75;
} else {
riskFactor = 1.0;
}
Java class RiskRater accepts the age and number of claims and passes those values to the scripting engine as well as the text of risk.js then prints the result.
import javax.script.*;
import java.io.FileReader;
public class RiskRater {
public static void main(String[] args) {
int age = Integer.parseInt(args[0]);
int nbrClaims = Integer.parseInt(args[1]);
System.out.printf("Risk for age %d and %d claims is %f", age,
nbrClaims, RiskRater.getRiskByAge(age, nbrClaims));
}
public static Object getRiskByAge(int age, int nbrClaims) {
Double risk = 0.0;
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.put("age", age);
engine.put("nbrClaims", nbrClaims);
engine.eval(new FileReader("risk.js"));
risk = (Double)engine.get("riskFactor");
} catch(Exception e) {
e.printStackTrace();
}
return risk;
}
}