import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; /* Java application that is intended to test the methods in the ** PrefixExprEvaluator class. It repeatedly reads lines of text ** from a file (if the name of a file is provided via command line ** argument) or (if not) from the keyboard. Each line is tested to see ** if it is a syntactically valid arithmetic expression in prefix form. ** If it is, it is evaluated. ** When a blank line is provided as input, the program terminates. ** ** Author: R. McCloskey ** Date: Oct. 2024 */ public class PrefixExprEvalApp { private static Scanner input; private static boolean echo; public static void main(String[] args) { establishScanner(args); boolean keepGoing = true; PrefixExprEvaluator evaluator = new PrefixExprEvaluator(); do { String expr = getResponse("\n> "); if (expr.length() == 0) { keepGoing = false; } else if (!evaluator.isValid(expr)) { System.out.println("<---- That is not a valid prefix expression"); } else { System.out.println(evaluator.valueOf(expr)); } } while (keepGoing); System.out.println("Goodbye."); } /* Assigns to global variable 'input' a Scanner able to read from ** the file whose name is args[0], assuming that args.length != 0. ** Otherwise, makes 'input' able to read from standard input. ** Also sets 'echo' to true in the former case, false in the latter, ** so that input data read from a file will appear in the produced ** output. */ private static void establishScanner(String[] args) { if (args.length != 0) { try { input = new Scanner(new File(args[0])); echo = true; } catch (FileNotFoundException e) { e.printStackTrace(System.out); System.out.println("Program aborting."); System.exit(0); } } else { input = new Scanner(System.in); echo = false; } } /* Prints the given prompt and returns the next line read in ** by the input Scanner. */ private static String getResponse(String prompt) { System.out.print(prompt); String result = input.nextLine().trim(); if (echo) { System.out.println(result); } return result; } }