<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 for simple expressions.
 */
public class SimpleExpression {
    
    /**
     * Main program.
     */
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        while (line.length() != 0) {
            System.out.println(line);
            Scanner scanner = new Scanner(line);
            try {
                parseE(scanner);
                if (!scanner.hasNext()) System.out.println("Valid");
                else System.err.println("Invalid: line has extra token = " + scanner.next());
            } catch (RuntimeException e) {
                System.err.println("Invalid: " + e.getMessage());
            }
            line = sc.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
     * @throws RuntimeException if parsing fails
     */
    public static void parseE(Scanner scanner) {
        if (scanner.hasNextInt()) scanner.nextInt();
        else {
            check(scanner, "(");
            parseE(scanner);
            check(scanner, "+");
            parseE(scanner);
            check(scanner, ")");
        }
    }
}</pre></body></html>