<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">import java.util.Scanner;

/**
 * Parser &amp; code generator for simple expressions.
 */
public class SimpleExpressionCodeGenerator {
    
    /**
     * Main program.
     */
    public static void main (String[] args) {
        String code;                   // Holds the generated code
        Scanner lineScanner = new Scanner(System.in);
        String line = lineScanner.nextLine();
        while (line.length() != 0) {
            System.out.println(line);
            Scanner scanner = new Scanner(line);
            try {
                code = parseE(scanner) + "STOP\n";
                if (scanner.hasNext()) 
                    throw new RuntimeException("Line has extra token = " + scanner.next());
            } catch (RuntimeException e) {
                System.err.println(e.getMessage());
                code = "ERROR\n";
            }
            System.out.println(code);
            line = lineScanner.nextLine();
        }
        System.out.println("Quitting");
    }
        
    /**
     * Check that scanner's next token matches the given string.
     * @param scanner the scanner
     * @param string the String to look for
     * @throws RuntimeException if check fails
     */
    public static void check (Scanner scanner, String string) {
        if (!scanner.hasNext()) throw new RuntimeException("Expected more input");
        String token = scanner.next();
        if (token.equals(string)) return;
        throw new RuntimeException("Expected " + string + ", but found " + token);
    }
    
    /**
     * Parse E, a simple expression.
     * @param scanner the scanner
     * @return the code for this expression
     * @throws RuntimeException if parsing fails
     */
    public static String parseE (Scanner scanner) {
        if (scanner.hasNextInt()) return "PUSH " + scanner.nextInt() + "\n";
        else {
            check(scanner, "(");
            String c1 = parseE(scanner);
            check(scanner, "+");
            String c2 = parseE(scanner);
            check(scanner, ")");
            return c1 + c2 + "ADD\n";
        }
    }
}</pre></body></html>