import java.util.NoSuchElementException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; /** * Does parsing of simple expressions. * This version has only a main program; you have to provide the rest. */ class Parser { /* * You will need to create fields and methods here. The fields * are used to maintain the current state of the parser. Useful * fields might include the current expression being parsed, the * ExpressionTokenizer, and the current values of x and y. * You need to create a constructor, and methods for * expression, term, and factor. You may find it useful to create * additional methods and fields. */ /** * Main program reads expressions, one per line, and evaluates * them. Takes a single command-line arg specifying the * size of the matrix on which the expression is evaluated. */ public static void main (String[] arg) { int size = 1; // Size of the output matrix String expression; // Input expression Parser parser; // The parser/evaluator // Look for a command line argument if (arg.length != 1) { System.out.println("Need a command line argument."); System.out.println("In CodeWarrior, select 'Java Application Settings...' in the Edit menu."); System.out.println("Place your argument in the 'Parameters' box."); throw new IllegalArgumentException(); } // Determine the size of the output matrix try { size = Integer.parseInt(arg[0]); } catch (NumberFormatException e) { System.out.println("Bad number on command line."); throw new IllegalArgumentException(); } // Prepare the standard input for reading lines BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Read expressions, one per line, until an empty line is read while (true) { try { System.out.print("Input: "); expression = in.readLine(); if (expression.equals("")) break; parser = new Parser(expression); // Print the output in matrix form for (int j = 0; j < size; j++) { for (int i = 0; i < size; i++) { System.out.print(parser.evaluate(i,j) + " "); } System.out.println(); } } // This exception occurs if you read past end-of-line catch (NoSuchElementException e) { System.out.println("Read past end-of-file"); } // This exception occurs when a failed attempt is made to // convert a String into a Double using Double.valueOf() catch (NumberFormatException e) { System.out.println("Badly formed number"); } // This exception should occur if something goes wrong // while parsing; the message should be helpful. catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } // This shouldn't occur, but is required when reading // from a file. catch (IOException e) { System.out.println("Unknown IO problem."); } } } }