Guest User

ExprEvaluatorTest.java

a guest
Feb 24th, 2022
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1.  
  2.  
  3. /* program to test the expression evaluator; evaluates input arithmetic expressions, each
  4. represented as a string without blanks, and with negative numbers indicated by underscore.
  5. Declare an expression using either ExprEvaluator exp = new ExprEvaluator()
  6. (and respond to the prompt), or as ExprEvaluator exp = new ExprEvaluator("expression string").
  7. The expression can be returned as a String using exp.getExpression().
  8. The expression can be evaluated using exp.evaluator(), which also displays the result
  9. rounded to 7 decimal places, supressing a decimal point if the result is an integer.
  10. The computed value is also returned as a double.
  11. */
  12.  
  13. public class ExprEvaluatorTest
  14. {
  15.  
  16. public static void main(String[] args)
  17. {
  18.  
  19. //initialize several expressions, but do not evaluate them immediately
  20. ExprEvaluator expr1 = new ExprEvaluator(); //construct an expression via keyboard
  21. ExprEvaluator expr2 = new ExprEvaluator("3+4."); //enter an expression via string parameter
  22. ExprEvaluator expr3 = new ExprEvaluator("(3.+4*(1+2*(4+3*(2-_7)))-1)/2.0");
  23.  
  24. //display the input for expr1
  25. System.out.println(expr1.getExpression() + '\n');
  26. expr1.evaluator(); //evaluate expr1
  27.  
  28. expr2.evaluator(); //evaluate expr2; the result will appear as an int value
  29.  
  30. System.out.println(expr3.evaluator());
  31. //the evaluator() method will display the result as an int value
  32. //the value is also returned as a double to the print statement
  33.  
  34. expr1 = new ExprEvaluator("3.1415927"); //a single number is also an expression
  35. System.out.println(Math.pow(expr1.evaluator(),2)); //the call to evaluator displays
  36. //the value, which is then squared by pow
  37.  
  38. expr2 = new ExprEvaluator("3.1415927*3.1415927");
  39. expr2.evaluator(); //we can compare (to 7 places) the Java value using pow to the value using evaluator
  40.  
  41. }
  42.  
  43. }
Advertisement
Add Comment
Please, Sign In to add comment