Advertisement
Imran2544

Evaluate expression in Java using rhino (Javascript)

Oct 23rd, 2020 (edited)
2,292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.19 KB | None | 0 0
  1. // Inside Gradle Scripts -> dependencies
  2. implementation 'com.faendir.rhino:rhino-android:1.5.2'
  3.  
  4. // Equal method
  5. btnEqual.setOnClickListener(new View.OnClickListener() {
  6.     @Override
  7.     public void onClick(View v) {
  8.         String text = input.getText().toString();
  9.  
  10.         if ("".equals(text)) {
  11.             startPar = false;
  12.             return;
  13.         }
  14.  
  15.         output.setText(text);
  16.  
  17.         text = text.replaceAll("รท", "/");
  18.         text = text.replaceAll("%", "/100");
  19.         text = text.replaceAll("ร—", "*");
  20.         text = text.replaceAll("โˆ’", "-");
  21.         text = text.replaceAll("Mod", "%");
  22.  
  23.         org.mozilla.javascript.Context rhino = Context.enter();
  24.  
  25.         rhino.setOptimizationLevel(-1);
  26.  
  27.  
  28.         String result = "";
  29.  
  30.         try {
  31.             Scriptable scriptable = rhino.initStandardObjects();
  32.             result = rhino.evaluateString(scriptable, text, "javascript", 1, null).toString();
  33.         }
  34.         catch (Exception e) {
  35.             result = "0";
  36.         }
  37.  
  38.         if (result.length() > 10) {
  39.             input.setTextSize(TypedValue.COMPLEX_UNIT_SP, 37);
  40.         }
  41.  
  42.         input.setText(result);
  43.         startPar = false;
  44.     }
  45. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement