Question: EvaluateDemonstration.java import java.util.Stack; import java.util.Scanner; import java.util.regex.Pattern; public class EvaluateDemonstration { public static void main(String[ ] args) { Scanner stdin = new Scanner(System.in); String expression;

EvaluateDemonstration.java
import java.util.Stack; import java.util.Scanner; import java.util.regex.Pattern;
public class EvaluateDemonstration { public static void main(String[ ] args) { Scanner stdin = new Scanner(System.in); String expression; double answer; System.out.println("Please type an arithmetic expression made from"); System.out.println("unsigned numbers and the operations + - * /."); System.out.println("The expression must be fully parenthesized.");
do { System.out.print("Your expression: "); expression = stdin.nextLine( ); try { answer = evaluate(expression); System.out.println("The value is " + answer); } catch (Exception e) { System.out.println("Error." + e.toString( )); } } while (query(stdin, "Another string?"));
System.out.println("All numbers are interesting."); }
public static boolean query(Scanner input, String prompt) { String answer; System.out.print(prompt + " [Y or N]: "); answer = input.nextLine( ).toUpperCase( ); while (!answer.startsWith("Y") && !answer.startsWith("N")) { System.out.print("Invalid response. Please type Y or N: "); answer = input.nextLine( ).toUpperCase( ); }
return answer.startsWith("Y"); }
public static double evaluate(String s) // Precondition: The string is a fully parenthesized arithmetic expression // formed from non-negative numbers, parentheses, and the four operations // +, -, *, and /. // Postcondition: The string has been evaluated and the value returned. // Exceptions: Can throw an NumberFormatException if the expression contains // characters other than digits, operations, parentheses and whitespace. // Can throw IllegalArgumentException if the input line is an // illegal expression, such as unbalanced parentheses or a division by zero. { Scanner input = new Scanner(s); Stack // These patterns are from Appendix B of Data Structures and Other Objects. // They may be used in hasNext and findInLine to read certain patterns // from a Scanner. public static final Pattern CHARACTER = Pattern.compile("\S.*?"); public static final Pattern UNSIGNED_DOUBLE = Pattern.compile("((\d+\.?\d*)|(\.\d+))([Ee][-+]?\d+)?.*?"); }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
