Class Console

  • All Implemented Interfaces:
    java.awt.event.KeyListener, java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, javax.accessibility.Accessible
    Direct Known Subclasses:
    BigDecimalConsole, CPConsole, DJepConsole, FieldConsole, LambdaConsole, MatrixConsole, MrpEvalConsole, PostfixEvaluationConsole, PrefixDumperConsole, PrintConsole, RpEvalConsole, StructuredConsole, VectorConsole, XJepConsole

    public class Console
    extends java.applet.Applet
    implements java.awt.event.KeyListener
    This class implements a simple command line utility for evaluating mathematical expressions.
       Usage: java com.singularsys.jepexamples.consoles.Console [expression]
     
    If an argument is passed, it is interpreted as an expression and evaluated. Otherwise, a prompt is printed, and the user can enter expressions to be evaluated.

    This class and its subclasses can also be run as a java applet which displays a textarea for interactive input.

    This class has been designed to be sub classed to allow different consol applications. The methods

     public void initialise()
     public Object processEquation(Node node) throws Exception
     public boolean testSpecialCommands(String command)
     public void printPrompt()
     public void printIntroText()
     public void printHelp()
     
    can all be overwritten.

    Furthermore main should be overwritten. For example

     
            public static void main(String args[]) {
                    Console c = new DJepConsole();
                    c.run(args);
            }
    

    The main input loop is approximately

     initialise();
     printIntroText();
     print(getPrompt());
     String command;
     while((command = getCommand()) != null) 
     {
            if(command.equals("quit") || command.equals("exit"))
                    break;
            if(!testSpecialCommands(command)) continue;
       try {
              Node n = j.parse(command);
              processEquation(n);
       } catch(Exception e) {}
            print(getPrompt());
     }
    
    See Also:
    Serialized Form
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      protected class  Console.JepPrintStream  
      static class  Console.SPEC_ACTION
      Values returned by @link{testSpecialCommands(String command)}.
      • Nested classes/interfaces inherited from class java.applet.Applet

        java.applet.Applet.AccessibleApplet
      • Nested classes/interfaces inherited from class java.awt.Panel

        java.awt.Panel.AccessibleAWTPanel
      • Nested classes/interfaces inherited from class java.awt.Container

        java.awt.Container.AccessibleAWTContainer
      • Nested classes/interfaces inherited from class java.awt.Component

        java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
    • Field Summary

      Fields 
      Modifier and Type Field Description
      protected java.lang.String doubleFormat
      Format for double output
      protected java.util.List<java.lang.String> history
      History
      protected Jep jep
      Main Jep object
      protected boolean showHistory  
      protected java.awt.TextArea ta
      Text area for user input in applets.
      • Fields inherited from class java.awt.Component

        BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
      • Fields inherited from interface java.awt.image.ImageObserver

        ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
    • Constructor Summary

      Constructors 
      Constructor Description
      Console()
      Constructor
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      java.lang.String getAppletInfo()  
      protected java.lang.String getCommand()
      Get a command from the input.
      java.lang.String getPrompt()
      Prints the prompt string.
      boolean handleError​(java.lang.Exception e)
      Handle an error in the parse and evaluate routines.
      void init()
      Applet initialisation
      void initialise()
      sets up all the needed objects.
      void inputLoop()
      The main input loop for interactive operation.
      void keyPressed​(java.awt.event.KeyEvent arg0)  
      void keyReleased​(java.awt.event.KeyEvent event)
      Handles keyRelease events
      void keyTyped​(java.awt.event.KeyEvent arg0)  
      static void main​(java.lang.String[] args)
      Creates a new Console object and calls run()
      void print​(java.lang.Object o)
      Prints a line of text no newline.
      void printFuns()
      Prints a list of defined functions.
      void printHelp()
      Print help message.
      void printIntroText()
      Prints introductory text.
      void println​(java.lang.Object o)
      Prints a line of text followed by a newline.
      void printOps()
      Prints a list of defined operators.
      void printStdHelp()
      Prints a standard help message.
      void printVars()
      Prints a list of variable.
      boolean processCommand​(java.lang.String command)
      Process a single command.
      java.lang.Object processEquation​(Node node)
      Performs the required operation on a node.
      void run​(java.lang.String[] args)
      The main entry point with command line arguments
      void setAlteredCommand​(java.lang.String alt)
      Set the command used if @link{SPEC_ACTION.ALTERED} returned.
      void setFormat​(java.lang.String format)  
      java.lang.String[] split​(java.lang.String s)
      Splits a string on spaces.
      Console.SPEC_ACTION testSpecialCommands​(java.lang.String command)
      Checks for special commands.
      java.lang.String toString​(java.lang.Object o)
      Return string representation of object.
      • Methods inherited from class java.applet.Applet

        destroy, getAccessibleContext, getAppletContext, getAudioClip, getAudioClip, getCodeBase, getDocumentBase, getImage, getImage, getLocale, getParameter, getParameterInfo, isActive, isValidateRoot, newAudioClip, play, play, resize, resize, setStub, showStatus, start, stop
      • Methods inherited from class java.awt.Panel

        addNotify
      • Methods inherited from class java.awt.Container

        add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getInsets, getLayout, getListeners, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, paramString, preferredSize, print, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, removeNotify, setComponentZOrder, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, setLayout, transferFocusDownCycle, update, validate, validateTree
      • Methods inherited from class java.awt.Component

        action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphics, getGraphicsConfiguration, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getToolkit, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, requestFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, requestFocusInWindow, reshape, revalidate, setBackground, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setMinimumSize, setMixingCutoutShape, setName, setPreferredSize, setSize, setSize, setVisible, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Field Detail

      • jep

        protected Jep jep
        Main Jep object
      • ta

        protected java.awt.TextArea ta
        Text area for user input in applets.
      • doubleFormat

        protected java.lang.String doubleFormat
        Format for double output
      • history

        protected java.util.List<java.lang.String> history
        History
      • showHistory

        protected boolean showHistory
    • Constructor Detail

      • Console

        public Console()
        Constructor
    • Method Detail

      • init

        public void init()
        Applet initialisation
        Overrides:
        init in class java.applet.Applet
      • initialise

        public void initialise()
        sets up all the needed objects.
      • main

        public static void main​(java.lang.String[] args)
        Creates a new Console object and calls run()
      • run

        public void run​(java.lang.String[] args)
        The main entry point with command line arguments
      • inputLoop

        public void inputLoop()
        The main input loop for interactive operation. Repeatedly calls getCommand() and processCommand().
      • processCommand

        public boolean processCommand​(java.lang.String command)
        Process a single command.
        1. Calls testSpecialCommands(String)
        2. Tests for exit, break, and altered results.
        3. Adds the command to the history.
        4. Parses the command.
        5. Calls processEquation(Node)
        6. Checks for errors, calling handleError(Exception) in necessary
        Parameters:
        command - The line to be processed
        Returns:
        false if un-recoverable error or 'quit' or 'exit'
      • processEquation

        public java.lang.Object processEquation​(Node node)
                                         throws JepException
        Performs the required operation on a node. Typically evaluates the node and prints the value.
        Parameters:
        node - Node representing expression
        Returns:
        The result of the calculation
        Throws:
        JepException - if a Parse or evaluation error
      • getCommand

        protected java.lang.String getCommand()
        Get a command from the input.
        Returns:
        null if an IO error or EOF occurs.
      • getPrompt

        public java.lang.String getPrompt()
        Prints the prompt string.
      • printStdHelp

        public final void printStdHelp()
        Prints a standard help message. Type 'quit' or 'exit' to quit, 'help' for help.
      • printHelp

        public void printHelp()
        Print help message.
      • printIntroText

        public void printIntroText()
        Prints introductory text.
      • printFuns

        public void printFuns()
        Prints a list of defined functions.
      • printOps

        public void printOps()
        Prints a list of defined operators.
      • printVars

        public void printVars()
        Prints a list of variable.
      • testSpecialCommands

        public Console.SPEC_ACTION testSpecialCommands​(java.lang.String command)
        Checks for special commands. For example a subclass may have a verbose mode switched on of off using the command
         verbose on
         
        This method can be used detected this input, perform required actions and skip normal processing by returning true. In general sub classes should call the superclass methods to test for special commands that class implements
        Parameters:
        command -
        Returns:
        SPEC_ACTION.CONTINUE - continue processing this equation, SPEC_ACTION.BREAK - stop processing this equation and get the next line of input, SPEC_ACTION.ALTERED - the input text has been altered, SPEC_ACTION.EXIT stop the program
        See Also:
        split(String)
      • setAlteredCommand

        public void setAlteredCommand​(java.lang.String alt)
        Set the command used if @link{SPEC_ACTION.ALTERED} returned.
        Parameters:
        alt -
      • setFormat

        public void setFormat​(java.lang.String format)
      • handleError

        public boolean handleError​(java.lang.Exception e)
        Handle an error in the parse and evaluate routines. Default is to print the error message for JepExceptions and a stack trace for other exceptions
        Parameters:
        e -
        Returns:
        false if the error cannot be recovered and the program should exit
      • split

        public java.lang.String[] split​(java.lang.String s)
        Splits a string on spaces.
        Parameters:
        s - the input string
        Returns:
        an array of the tokens in the string
      • print

        public void print​(java.lang.Object o)
        Prints a line of text no newline. Subclasses should call this method rather than System.out.print to allow for output to different places.
      • toString

        public java.lang.String toString​(java.lang.Object o)
        Return string representation of object. Used the doubleFormat if specified.
        Parameters:
        o -
        Returns:
      • println

        public void println​(java.lang.Object o)
        Prints a line of text followed by a newline. Subclasses should call this method rather than System.out.print to allow for output to different places.
      • keyReleased

        public void keyReleased​(java.awt.event.KeyEvent event)
        Handles keyRelease events
        Specified by:
        keyReleased in interface java.awt.event.KeyListener
      • keyPressed

        public void keyPressed​(java.awt.event.KeyEvent arg0)
        Specified by:
        keyPressed in interface java.awt.event.KeyListener
      • keyTyped

        public void keyTyped​(java.awt.event.KeyEvent arg0)
        Specified by:
        keyTyped in interface java.awt.event.KeyListener
      • getAppletInfo

        public java.lang.String getAppletInfo()
        Overrides:
        getAppletInfo in class java.applet.Applet