Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. String y = "2*y+1";
  2. int x = y;
  3. drawgraph(x);
  4.  
  5. import javax.script.*;
  6.  
  7. interface GraphFunction {
  8. double eval(double x);
  9.  
  10. public static GraphFunction createFromString(String expression) {
  11. try {
  12. ScriptEngine engine = new ScriptEngineManager()
  13. .getEngineByName("JavaScript");
  14. engine.eval("function graphFunc(x) { return " + expression + "; }");
  15. final Invocable inv = (Invocable)engine;
  16. return new GraphFunction() {
  17. @Override
  18. public double eval(double x) {
  19. try {
  20. return (double)inv.invokeFunction("graphFunc", x);
  21. } catch (NoSuchMethodException | ScriptException e) {
  22. throw new RuntimeException(e);
  23. }
  24. }
  25. };
  26. } catch (ScriptException e) {
  27. throw new RuntimeException(e);
  28. }
  29. }
  30. }
  31.  
  32. class Test {
  33. public static void main(String[] args) {
  34. GraphFunction f = GraphFunction.createFromString("2*x+1");
  35.  
  36. for (int x = -5; x <= +5; x++) {
  37. double y = f.eval(x);
  38. System.out.println(x + " => " + y);
  39. }
  40. }
  41. }
  42.  
  43. -5 => -9.0
  44. -4 => -7.0
  45. -3 => -5.0
  46. -2 => -3.0
  47. -1 => -1.0
  48. 0 => 1.0
  49. 1 => 3.0
  50. 2 => 5.0
  51. 3 => 7.0
  52. 4 => 9.0
  53. 5 => 11.0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement