<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">/**
 * AddParserWithScanner -- Addition Parser
 * This does the same thing as AddParser, except it is
 * implemented using the new java.util.Scanner class
 * instead of the CS211In classes.
 */

import java.util.Scanner;
import java.io.*;

public class AddParserWithScanner {
   
   private static Scanner fIn;   //input source
   private static PrintStream fOut;  //output target
   
   public static void main(String[] args) throws FileNotFoundException {
      
      //set up I/O
      switch (args.length) {
         case 2: //file input &amp; output
            File inFile = new File(args[0]);
            File outFile = new File(args[1]);
            if (inFile.equals(outFile)) {
               System.out.println("Can't have input file = output file");
               return;
            }
            fIn = new Scanner(inFile);
            fOut = new PrintStream(outFile);
            break;
         case 1: //file input, console output
            fIn = new Scanner(new File(args[0]));
            fOut = new PrintStream(System.out);
            break;
         case 0: //console input &amp; output
            fIn = new Scanner(System.in);
            fOut = new PrintStream(System.out);
            fOut.println("Enter an expression:");
            break;
         default:
            System.out.println("Wrong number of args");
            return;
      }
      //delimiters are ( + ) and white space, including newline
      fIn.useDelimiter("[(+)\\s]");
      
      //parse input expressions, one on each line
      boolean result = true;
      while (result) {
         //parse expression and check for end of line
         result = checkSum() &amp;&amp; (scanPast("\\n") || scanPast("\\z"));
         fOut.println("Result: " + result);
      }
      //close I/O devices
      fIn.close();
      fOut.close();
   }

   //find sum of expression
   private static boolean checkSum() {
      // inspect current character from input stream
      if (scanPast("\\n") || scanPast("\\+") || scanPast("\\)")) return false;
      if (scanPast("\\(")) { //left paren?
         return checkSum()
            &amp;&amp; scanPast("\\+")
            &amp;&amp; checkSum()
            &amp;&amp; scanPast("\\)");
      } 
      if (fIn.hasNextInt()) { //integer?
         fIn.nextInt(); //scan past the integer
         return true;
      }
      return false;
   }
   
   private static boolean scanPast(String s) {
      //skip white space, but not newline
      fIn.skip("[\\s&amp;&amp;[^\\n]]*");
      //check if next char is  s, consume it if so
      return fIn.findWithinHorizon(s,1) != null;
   }
}</pre></body></html>