Advertisement
Guest User

Untitled

a guest
Jan 17th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.70 KB | None | 0 0
  1. import javax.script.ScriptEngineManager;
  2. import javax.script.ScriptEngine;
  3. import javax.script.ScriptException;
  4.  
  5. public class Test {
  6. public static void main(String[] args) throws ScriptException {
  7. ScriptEngineManager mgr = new ScriptEngineManager();
  8. ScriptEngine engine = mgr.getEngineByName("JavaScript");
  9. String foo = "40+2";
  10. System.out.println(engine.eval(foo));
  11. }
  12. }
  13.  
  14. public static double eval(final String str) {
  15. return new Object() {
  16. int pos = -1, ch;
  17.  
  18. void nextChar() {
  19. ch = (++pos < str.length()) ? str.charAt(pos) : -1;
  20. }
  21.  
  22. boolean eat(int charToEat) {
  23. while (ch == ' ') nextChar();
  24. if (ch == charToEat) {
  25. nextChar();
  26. return true;
  27. }
  28. return false;
  29. }
  30.  
  31. double parse() {
  32. nextChar();
  33. double x = parseExpression();
  34. if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
  35. return x;
  36. }
  37.  
  38. // Grammar:
  39. // expression = term | expression `+` term | expression `-` term
  40. // term = factor | term `*` factor | term `/` factor
  41. // factor = `+` factor | `-` factor | `(` expression `)`
  42. // | number | functionName factor | factor `^` factor
  43.  
  44. double parseExpression() {
  45. double x = parseTerm();
  46. for (;;) {
  47. if (eat('+')) x += parseTerm(); // addition
  48. else if (eat('-')) x -= parseTerm(); // subtraction
  49. else return x;
  50. }
  51. }
  52.  
  53. double parseTerm() {
  54. double x = parseFactor();
  55. for (;;) {
  56. if (eat('*')) x *= parseFactor(); // multiplication
  57. else if (eat('/')) x /= parseFactor(); // division
  58. else return x;
  59. }
  60. }
  61.  
  62. double parseFactor() {
  63. if (eat('+')) return parseFactor(); // unary plus
  64. if (eat('-')) return -parseFactor(); // unary minus
  65.  
  66. double x;
  67. int startPos = this.pos;
  68. if (eat('(')) { // parentheses
  69. x = parseExpression();
  70. eat(')');
  71. } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
  72. while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
  73. x = Double.parseDouble(str.substring(startPos, this.pos));
  74. } else if (ch >= 'a' && ch <= 'z') { // functions
  75. while (ch >= 'a' && ch <= 'z') nextChar();
  76. String func = str.substring(startPos, this.pos);
  77. x = parseFactor();
  78. if (func.equals("sqrt")) x = Math.sqrt(x);
  79. else if (func.equals("sin")) x = Math.sin(Math.toRadians(x));
  80. else if (func.equals("cos")) x = Math.cos(Math.toRadians(x));
  81. else if (func.equals("tan")) x = Math.tan(Math.toRadians(x));
  82. else throw new RuntimeException("Unknown function: " + func);
  83. } else {
  84. throw new RuntimeException("Unexpected: " + (char)ch);
  85. }
  86.  
  87. if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation
  88.  
  89. return x;
  90. }
  91. }.parse();
  92. }
  93.  
  94. System.out.println(eval("((4 - 2^3 + 1) * -sqrt(3*3+4*4)) / 2"));
  95.  
  96. @FunctionalInterface
  97. interface Expression {
  98. double eval();
  99. }
  100.  
  101. Expression parseExpression() {
  102. Expression x = parseTerm();
  103. for (;;) {
  104. if (eat('+')) { // addition
  105. Expression a = x, b = parseTerm();
  106. x = (() -> a.eval() + b.eval());
  107. } else if (eat('-')) { // subtraction
  108. Expression a = x, b = parseTerm();
  109. x = (() -> a.eval() - b.eval());
  110. } else {
  111. return x;
  112. }
  113. }
  114. }
  115.  
  116. public static void main(String[] args) {
  117. Map<String,Double> variables = new HashMap<>();
  118. Expression exp = parse("x^2 - x + 2", variables);
  119. for (double x = -20; x <= +20; x++) {
  120. variables.put("x", x);
  121. System.out.println(x + " => " + exp.eval());
  122. }
  123. }
  124.  
  125. Interpreter interpreter = new Interpreter();
  126. interpreter.eval("result = (7+21*6)/(32-27)");
  127. System.out.println(interpreter.get("result"));
  128.  
  129. select (((12.10 +12.0))/ 233.0) amount
  130.  
  131. select (((12.10 +12.0))/ 233.0) amount from dual;
  132.  
  133. Class. forName("org.sqlite.JDBC");
  134. Connection conn = DriverManager.getConnection("jdbc:sqlite::memory:");
  135. Statement stat = conn.createStatement();
  136. ResultSet rs = stat.executeQuery( "select (1+10)/20.0 amount");
  137. rs.next();
  138. System.out.println(rs.getBigDecimal(1));
  139. stat.close();
  140. conn.close();
  141.  
  142. ResultSet rs = stat.executeQuery( "select (1+10)/20.0 amount, (1+100)/20.0 amount2");
  143.  
  144. Expression e = new Expression("( 2 + 3/4 + sin(pi) )/2");
  145. double v = e.calculate()
  146.  
  147. Argument x = new Argument("x = 10");
  148. Constant a = new Constant("a = pi^2");
  149. Expression e = new Expression("cos(a*x)", x, a);
  150. double v = e.calculate()
  151.  
  152. Function f = new Function("f(x, y, z) = sin(x) + cos(y*z)");
  153. Expression e = new Expression("f(3,2,5)", f);
  154. double v = e.calculate()
  155.  
  156. Expression e = new Expression("sum( i, 1, 100, sin(i) )");
  157. double v = e.calculate()
  158.  
  159. ExpressionParser parser = new SpelExpressionParser();
  160. int two = parser.parseExpression("1 + 1").getValue(Integer.class); // 2
  161. double twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Double.class); //24.0
  162.  
  163. ExpressionsEvaluator evalExpr = ExpressionsFactory.create("2+3*4-6/2");
  164. assertEquals(BigDecimal.valueOf(11), evalExpr.eval());
  165.  
  166. String math = "1+4";
  167.  
  168. if (math.split("+").length == 2) {
  169. //do calculation
  170. } else if (math.split("-").length == 2) {
  171. //do calculation
  172. } ...
  173.  
  174. 1 While the thing on top of the operator stack is not a
  175. left parenthesis,
  176. 1 Pop the operator from the operator stack.
  177. 2 Pop the value stack twice, getting two operands.
  178. 3 Apply the operator to the operands, in the correct order.
  179. 4 Push the result onto the value stack.
  180. 2 Pop the left parenthesis from the operator stack, and discard it.
  181.  
  182. 1 While the operator stack is not empty, and the top thing on the
  183. operator stack has the same or greater precedence as thisOp,
  184. 1 Pop the operator from the operator stack.
  185. 2 Pop the value stack twice, getting two operands.
  186. 3 Apply the operator to the operands, in the correct order.
  187. 4 Push the result onto the value stack.
  188. 2 Push thisOp onto the operator stack.
  189.  
  190. ExprEvaluator util = new ExprEvaluator();
  191. IExpr result = util.evaluate("10-40");
  192. System.out.println(result.toString()); // -> "-30"
  193.  
  194. // D(...) gives the derivative of the function Sin(x)*Cos(x)
  195. IAST function = D(Times(Sin(x), Cos(x)), x);
  196. IExpr result = util.evaluate(function);
  197. // print: Cos(x)^2-Sin(x)^2
  198.  
  199. public static double eval(final String str) {
  200. return new Object() {
  201. int pos = -1, ch;
  202.  
  203. void nextChar() {
  204. ch = (++pos < str.length()) ? str.charAt(pos) : -1;
  205. }
  206.  
  207. boolean eat(int charToEat) {
  208. while (ch == ' ') nextChar();
  209. if (ch == charToEat) {
  210. nextChar();
  211. return true;
  212. }
  213. return false;
  214. }
  215.  
  216. double parse() {
  217. nextChar();
  218. double x = parseExpression();
  219. if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
  220. return x;
  221. }
  222.  
  223. // Grammar:
  224. // expression = term | expression `+` term | expression `-` term
  225. // term = factor | term `*` factor | term `/` factor
  226. // factor = `+` factor | `-` factor | `(` expression `)`
  227. // | number | functionName factor | factor `^` factor
  228.  
  229. double parseExpression() {
  230. double x = parseTerm();
  231. for (;;) {
  232. if (eat('+')) x += parseTerm(); // addition
  233. else if (eat('-')) x -= parseTerm(); // subtraction
  234. else return x;
  235. }
  236. }
  237.  
  238. double parseTerm() {
  239. double x = parseFactor();
  240. for (;;) {
  241. if (eat('*')) x *= parseFactor(); // multiplication
  242. else if (eat('/')) x /= parseFactor(); // division
  243. else if (eat('^')) x = Math.pow(x, parseFactor()); //exponentiation -> Moved in to here. So the problem is fixed
  244. else return x;
  245. }
  246. }
  247.  
  248. double parseFactor() {
  249. if (eat('+')) return parseFactor(); // unary plus
  250. if (eat('-')) return -parseFactor(); // unary minus
  251.  
  252. double x;
  253. int startPos = this.pos;
  254. if (eat('(')) { // parentheses
  255. x = parseExpression();
  256. eat(')');
  257. } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
  258. while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
  259. x = Double.parseDouble(str.substring(startPos, this.pos));
  260. } else if (ch >= 'a' && ch <= 'z') { // functions
  261. while (ch >= 'a' && ch <= 'z') nextChar();
  262. String func = str.substring(startPos, this.pos);
  263. x = parseFactor();
  264. if (func.equals("sqrt")) x = Math.sqrt(x);
  265. else if (func.equals("sin")) x = Math.sin(Math.toRadians(x));
  266. else if (func.equals("cos")) x = Math.cos(Math.toRadians(x));
  267. else if (func.equals("tan")) x = Math.tan(Math.toRadians(x));
  268. else throw new RuntimeException("Unknown function: " + func);
  269. } else {
  270. throw new RuntimeException("Unexpected: " + (char)ch);
  271. }
  272.  
  273. //if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation -> This is causing a bit of problem
  274.  
  275. return x;
  276. }
  277. }.parse();
  278. }
  279.  
  280. import javax.script.ScriptEngine;
  281. import javax.script.ScriptEngineManager;
  282.  
  283. public class EvalUtil {
  284. private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
  285. public static void main(String[] args) {
  286. try {
  287. System.out.println((new EvalUtil()).eval("(((5+5)/2) > 5) || 5 >3 "));
  288. System.out.println((new EvalUtil()).eval("(((5+5)/2) > 5) || true"));
  289. } catch (Exception e) {
  290. e.printStackTrace();
  291. }
  292. }
  293. public Object eval(String input) throws Exception{
  294. try {
  295. if(input.matches(".*[a-zA-Z;~`#$_{}\[\]:\\;"',\.\?]+.*")) {
  296. throw new Exception("Invalid expression : " + input );
  297. }
  298. return engine.eval(input);
  299. } catch (Exception e) {
  300. e.printStackTrace();
  301. throw e;
  302. }
  303. }
  304. }
  305.  
  306. package ExpressionCalculator.expressioncalculator;
  307.  
  308. import java.text.DecimalFormat;
  309. import java.util.Scanner;
  310.  
  311. public class ExpressionCalculator {
  312.  
  313. private static String addSpaces(String exp){
  314.  
  315. //Add space padding to operands.
  316. //https://regex101.com/r/sJ9gM7/73
  317. exp = exp.replaceAll("(?<=[0-9()])[\/]", " / ");
  318. exp = exp.replaceAll("(?<=[0-9()])[\^]", " ^ ");
  319. exp = exp.replaceAll("(?<=[0-9()])[\*]", " * ");
  320. exp = exp.replaceAll("(?<=[0-9()])[+]", " + ");
  321. exp = exp.replaceAll("(?<=[0-9()])[-]", " - ");
  322.  
  323. //Keep replacing double spaces with single spaces until your string is properly formatted
  324. /*while(exp.indexOf(" ") != -1){
  325. exp = exp.replace(" ", " ");
  326. }*/
  327. exp = exp.replaceAll(" {2,}", " ");
  328.  
  329. return exp;
  330. }
  331.  
  332. public static Double evaluate(String expr){
  333.  
  334. DecimalFormat df = new DecimalFormat("#.####");
  335.  
  336. //Format the expression properly before performing operations
  337. String expression = addSpaces(expr);
  338.  
  339. try {
  340. //We will evaluate using rule BDMAS, i.e. brackets, division, power, multiplication, addition and
  341. //subtraction will be processed in following order
  342. int indexClose = expression.indexOf(")");
  343. int indexOpen = -1;
  344. if (indexClose != -1) {
  345. String substring = expression.substring(0, indexClose);
  346. indexOpen = substring.lastIndexOf("(");
  347. substring = substring.substring(indexOpen + 1).trim();
  348. if(indexOpen != -1 && indexClose != -1) {
  349. Double result = evaluate(substring);
  350. expression = expression.substring(0, indexOpen).trim() + " " + result + " " + expression.substring(indexClose + 1).trim();
  351. return evaluate(expression.trim());
  352. }
  353. }
  354.  
  355. String operation = "";
  356. if(expression.indexOf(" / ") != -1){
  357. operation = "/";
  358. }else if(expression.indexOf(" ^ ") != -1){
  359. operation = "^";
  360. } else if(expression.indexOf(" * ") != -1){
  361. operation = "*";
  362. } else if(expression.indexOf(" + ") != -1){
  363. operation = "+";
  364. } else if(expression.indexOf(" - ") != -1){ //Avoid negative numbers
  365. operation = "-";
  366. } else{
  367. return Double.parseDouble(expression);
  368. }
  369.  
  370. int index = expression.indexOf(operation);
  371. if(index != -1){
  372. indexOpen = expression.lastIndexOf(" ", index - 2);
  373. indexOpen = (indexOpen == -1)?0:indexOpen;
  374. indexClose = expression.indexOf(" ", index + 2);
  375. indexClose = (indexClose == -1)?expression.length():indexClose;
  376. if(indexOpen != -1 && indexClose != -1) {
  377. Double lhs = Double.parseDouble(expression.substring(indexOpen, index));
  378. Double rhs = Double.parseDouble(expression.substring(index + 2, indexClose));
  379. Double result = null;
  380. switch (operation){
  381. case "/":
  382. //Prevent divide by 0 exception.
  383. if(rhs == 0){
  384. return null;
  385. }
  386. result = lhs / rhs;
  387. break;
  388. case "^":
  389. result = Math.pow(lhs, rhs);
  390. break;
  391. case "*":
  392. result = lhs * rhs;
  393. break;
  394. case "-":
  395. result = lhs - rhs;
  396. break;
  397. case "+":
  398. result = lhs + rhs;
  399. break;
  400. default:
  401. break;
  402. }
  403. if(indexClose == expression.length()){
  404. expression = expression.substring(0, indexOpen) + " " + result + " " + expression.substring(indexClose);
  405. }else{
  406. expression = expression.substring(0, indexOpen) + " " + result + " " + expression.substring(indexClose + 1);
  407. }
  408. return Double.valueOf(df.format(evaluate(expression.trim())));
  409. }
  410. }
  411. }catch(Exception exp){
  412. exp.printStackTrace();
  413. }
  414. return 0.0;
  415. }
  416.  
  417. public static void main(String args[]){
  418.  
  419. Scanner scanner = new Scanner(System.in);
  420. System.out.print("Enter an Mathematical Expression to Evaluate: ");
  421. String input = scanner.nextLine();
  422. System.out.println(evaluate(input));
  423. }
  424.  
  425. String st = "10+3";
  426. int result;
  427. for(int i=0;i<st.length();i++)
  428. {
  429. if(st.charAt(i)=='+')
  430. {
  431. result=Integer.parseInt(st.substring(0, i))+Integer.parseInt(st.substring(i+1, st.length()));
  432. System.out.print(result);
  433. }
  434. }
  435.  
  436. String expressionStr = "x+y";
  437. Map<String, Object> vars = new HashMap<String, Object>();
  438. vars.put("x", 10);
  439. vars.put("y", 20);
  440. ExecutableStatement statement = (ExecutableStatement) MVEL.compileExpression(expressionStr);
  441. Object result = MVEL.executeExpression(statement, vars);
  442.  
  443. import java.util.*;
  444. StringTokenizer st;
  445. int ans;
  446.  
  447. public class check {
  448. String str="7 + 5";
  449. StringTokenizer st=new StringTokenizer(str);
  450.  
  451. int v1=Integer.parseInt(st.nextToken());
  452. String op=st.nextToken();
  453. int v2=Integer.parseInt(st.nextToken());
  454.  
  455. if(op.equals("+")) { ans= v1 + v2; }
  456. if(op.equals("-")) { ans= v1 - v2; }
  457. //.........
  458. }
  459.  
  460. public class RhinoApp {
  461. private String simpleAdd = "(12+13+2-2)*2+(12+13+2-2)*2";
  462.  
  463. public void runJavaScript() {
  464. Context jsCx = Context.enter();
  465. Context.getCurrentContext().setOptimizationLevel(-1);
  466. ScriptableObject scope = jsCx.initStandardObjects();
  467. Object result = jsCx.evaluateString(scope, simpleAdd , "formula", 0, null);
  468. Context.exit();
  469. System.out.println(result);
  470. }
  471.  
  472. package test;
  473.  
  474. public class Calculator {
  475.  
  476. public static Double calculate(String expression){
  477. if (expression == null || expression.length() == 0) {
  478. return null;
  479. }
  480. return calc(expression.replace(" ", ""));
  481. }
  482. public static Double calc(String expression) {
  483.  
  484. if (expression.startsWith("(") && expression.endsWith(")")) {
  485. return calc(expression.substring(1, expression.length() - 1));
  486. }
  487. String[] containerArr = new String[]{expression};
  488. double leftVal = getNextOperand(containerArr);
  489. expression = containerArr[0];
  490. if (expression.length() == 0) {
  491. return leftVal;
  492. }
  493. char operator = expression.charAt(0);
  494. expression = expression.substring(1);
  495.  
  496. while (operator == '*' || operator == '/') {
  497. containerArr[0] = expression;
  498. double rightVal = getNextOperand(containerArr);
  499. expression = containerArr[0];
  500. if (operator == '*') {
  501. leftVal = leftVal * rightVal;
  502. } else {
  503. leftVal = leftVal / rightVal;
  504. }
  505. if (expression.length() > 0) {
  506. operator = expression.charAt(0);
  507. expression = expression.substring(1);
  508. } else {
  509. return leftVal;
  510. }
  511. }
  512. if (operator == '+') {
  513. return leftVal + calc(expression);
  514. } else {
  515. return leftVal - calc(expression);
  516. }
  517.  
  518. }
  519.  
  520. private static double getNextOperand(String[] exp){
  521. double res;
  522. if (exp[0].startsWith("(")) {
  523. int open = 1;
  524. int i = 1;
  525. while (open != 0) {
  526. if (exp[0].charAt(i) == '(') {
  527. open++;
  528. } else if (exp[0].charAt(i) == ')') {
  529. open--;
  530. }
  531. i++;
  532. }
  533. res = calc(exp[0].substring(1, i - 1));
  534. exp[0] = exp[0].substring(i);
  535. } else {
  536. int i = 1;
  537. if (exp[0].charAt(0) == '-') {
  538. i++;
  539. }
  540. while (exp[0].length() > i && isNumber((int) exp[0].charAt(i))) {
  541. i++;
  542. }
  543. res = Double.parseDouble(exp[0].substring(0, i));
  544. exp[0] = exp[0].substring(i);
  545. }
  546. return res;
  547. }
  548.  
  549.  
  550. private static boolean isNumber(int c) {
  551. int zero = (int) '0';
  552. int nine = (int) '9';
  553. return (c >= zero && c <= nine) || c =='.';
  554. }
  555.  
  556. public static void main(String[] args) {
  557. System.out.println(calculate("(((( -6 )))) * 9 * -1"));
  558. System.out.println(calc("(-5.2+-5*-5*((5/4+2)))"));
  559.  
  560. }
  561.  
  562. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement