Results 1 to 2 of 2
  1. #1
    alminster is offline Member
    Join Date
    Apr 2013
    Posts
    1
    Rep Power
    0

    Default Need GUI Help everything else works

    package expeval;


    /**
    * This defines the concept of an Expression. The expression is
    * implemented as an array of tokens: where each token contains
    * a string.
    *
    * @author Alex Menz
    * @version 2013
    */
    import java.util.*;
    public class Expression
    {
    //---------------------------------------------------------------------
    private ArrayList<Token> expression; //Expression is input as a String




    //---------------------------------------------------------------------
    /**
    * Constructor: The String exp contains the infix expression.
    * This breaks it into tokens and
    * stores them in an ArrayList.
    */
    public Expression(String exp)
    {
    //Create the array that represents the body of the Expression
    expression = new ArrayList<Token>();


    //Tokenize the expression using the String Tokenizer class.
    //Assumed that the tokens are seperated by spaces
    StringTokenizer strTok = new StringTokenizer(exp," ");

    //Scan the input expression from left to right for tokens
    while (strTok.hasMoreElements())
    {
    Token tok = new Token((String) strTok.nextElement());
    expression.add(tok);
    }
    }

    //---------------------------------------------------------------------
    /**
    * Alternative constructor. This creates an array with no tokens
    * in it.
    */
    public Expression()
    {
    //Create the array that represents the body of the Expression
    expression = new ArrayList<Token>();
    }

    public int size()
    {
    return expression.size();
    }


    //---------------------------------------------------------------------
    /**
    * Appending a token at the end of the expression
    */
    public void add(Token newElement)
    {
    expression.add(newElement);
    }

    //---------------------------------------------------------------------
    /**
    * Creates a printable string from the expression
    */
    public String toString()
    {
    String ret = "";
    for (int i = 0; i < expression.size(); i++)
    ret = ret + expression.get(i).getBody()+" ";
    return ret;
    }

    public ArrayList<Token> getExpression()
    {
    return expression;
    }
    }



    package expeval;


    /**
    * Arranges for the evaluation of an arithmetic expression
    *
    * @author Alex Menz
    * @version 2013
    */
    public class ExpressionEvaluator
    {

    public int evaluate(Expression infix)
    {
    //Instantiate an InfixToPostfixConverter
    InfixToPostfixConverter itop =
    new InfixToPostfixConverter(infix);

    //Convert infix to postfix
    itop.convertToPostfix();
    Expression postfix = itop.getPostfix();

    //Print the postfix
    System.out.println("Postfix Expression: "+postfix.toString());

    //Instantiate a PostfixEvaluator
    PostfixEvaluator peval = new PostfixEvaluator(postfix);

    //Evaluate the postfix expression
    int value = peval.eval();

    //Return the calculated value
    return value;

    }
    }



    //-----------------------------------------------------------------
    package expeval;


    /**
    * Tester class for ExpressionEvaluator
    *
    * @author Alex Menz
    * @version 2013
    */
    public class ExpressionEvaluatorTester
    {
    public static void main(String[] args)
    {
    //Expression z = new Expression ();
    //Create an array of Test Data
    Expression[] testExpressions =
    {
    new Expression("1 < 2"),
    new Expression("1 == 2"),
    new Expression("1 != 2"),
    new Expression("1 > 2"),
    new Expression("1 >= 2"),
    new Expression("1 <= 2"),
    new Expression("1 && 0"),
    new Expression("25 || 26"),
    new Expression("25 || 0"),
    new Expression("25 && 26"),
    new Expression("25 || 26 && 0"),
    new Expression("( 25 || 26 ) && 0"),
    new Expression("1 < 2 && 2 < 3"),
    new Expression("1 < 2 && 2 > 3"),
    new Expression("1 < 2 || 2 < 3"),
    new Expression("1 < 2 || 2 > 3"),
    new Expression("1 > 2 || 2 > 3"),
    new Expression("1 < 2 < 3"),
    new Expression("1 < 2 > 3"),
    new Expression("1 < 2 + 5"),
    new Expression("( 1 < 2 ) + 5"),
    new Expression("2 < 3 * 5 + 4"),
    new Expression("( 2 < 3 ) * ( 5 + 4 )"),
    new Expression("( 2 < 3 * 5 ) + 4"),
    new Expression("( 25 + ( 10 > 5 ) * 3 ) % 6"),
    new Expression("( 25 < 8 < 9 ) + ( 8 * 3 > 2 )"),
    new Expression("25 + 45"),
    new Expression("10 * ( 5 + 3 )"),
    new Expression("20"),
    new Expression("10 * 5 + 3 "),
    new Expression("10 * ( 7 + ( 12 - 9 ) ) / 10 "),
    new Expression("100 % ( ( 3 + 2 ) + 3 ) / 4 ")
    };

    //Instantiate an ExpressionEvaluator
    ExpressionEvaluator ee = new ExpressionEvaluator ();

    //For each expression in the array, print the expression,
    //evaluate the expression and print its value
    for (int i = 0; i < testExpressions.length; i++)
    {
    System.out.println("Infix Expression: "+testExpressions[i]);
    System.out.println("Value of Expression: "+ee.evaluate(testExpressions[i])+"\n\n");
    }
    }
    }


    package expeval;

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.text.*;

    public class ExpressionGUI extends JFrame{
    //------------------------------------------------------------------
    //System Imports

    /**
    * A GUI for the Application
    * @author Alex Menz
    *
    */

    //---------------------------------------------------------------
    // Declare GUI Components
    private Expression myExpression;
    private JLabel expression;
    private JLabel value;
    private JTextField expressionField;
    private JTextField valueField;
    private JButton evaluate;
    private JButton quit;

    //---------------------------------------------------------------
    // Constructor calls: instantiateGUIComponents(), buildGUI(), and
    // addListeners(); setDefaultCloseOperation, setSize(...) and
    // setVisible(true)
    public ExpressionGUI(Expression ex)
    {
    setMyExpression(ex);
    instantiateGUIComponents();
    buildGUI();
    addListeners();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400,300);
    setVisible(true);

    }
    //--------------------------------------------------------------
    private void instantiateGUIComponents()
    {
    expression = new JLabel(" Enter Infix Expression ");
    value = new JLabel(" Value Of Expression ");
    expressionField = new JTextField(100);
    valueField = new JTextField(10);
    evaluate = new JButton("Calculate");
    quit = new JButton("Exit");


    }


    //--------------------------------------------------------------
    private void buildGUI()
    {
    //--------------Get Content Pane to add components
    Container c = getContentPane();
    c.setLayout(new GridLayout(6,3,10,10));
    c.add(expression);
    c.add(value);
    c.add(expressionField);
    c.add(valueField);
    c.add(evaluate);
    c.add(quit);

    }

    //--------------------------------------------------------------
    /**
    * For each button, add an ActionListener object, which is
    * coded here; and specifies what action is taken when that
    * button is clicked.
    * @param arg0
    */

    private void addListeners()
    {
    evaluate.addActionListener(
    new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    // Expression z = new Expression ();

    String text = expressionField.getText();
    System.out.println(text);
    //z = (Expression) text
    // System.out.println("Value of Expression: "+z.evaluate());

    }
    });

    quit.addActionListener(
    new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    System.exit(0);
    }
    }
    );
    }
    public void setMyExpression(Expression myExpression) {
    this.myExpression = myExpression;
    }
    public Expression getMyExpression() {
    return myExpression;
    }
    }

    //-----------------------------------------------------------------
    package expeval;
    import stack.*;
    import java.util.*;

    /**
    * Converting an arithmetic expression from infix to postfix.
    * Assumptions:
    * Arithmetic expression has only integer operands
    * Only +, -, *, / and % operators are allowed.
    * Usual rules of precedence are assumed.
    * Parentheses are allowed.
    *
    * @author Alex Menz
    * @version 2013
    */
    public class InfixToPostfixConverter
    {
    // Expression to be converted
    private Expression infixExpression;

    //Largest size of the stack
    private final int MAXSTACKSIZE = 20;

    //Resulting postfix expression
    private Expression postfixExpression;

    /**
    * Constructor: Just assigns the parameter to instance variable
    */
    public InfixToPostfixConverter(Expression infix)
    {
    infixExpression = infix;
    }

    /**
    * Main conversion algorithm.
    */
    public void convertToPostfix()
    {
    //Create an empty postfix expression
    postfixExpression = new Expression();

    //create an empty operator stack
    ArrayStack<Token> operatorStack = new ArrayStack<Token>(MAXSTACKSIZE);

    //Temporary local variables
    Token nextToken = null;
    Token topOfStack = null;

    //Main loop
    ArrayList<Token> expr = infixExpression.getExpression();
    for (int k = 0; k < expr.size(); k++)
    {
    //Get the next token from infix expression
    nextToken = expr.get(k);

    //If it is an operand append it to postfix
    if (nextToken.isOperand())
    postfixExpression.add(nextToken);

    //If it is an open parenthesis push it into stack
    else if (nextToken.isOpenParen())
    operatorStack.push(nextToken);
    //If next token is a closed parenthesis
    else if (nextToken.isClosedParen())
    {
    //Keep pulling operators out of stack and appending
    //them to postfix, until top of stack is an open paren
    topOfStack = operatorStack.top();
    while (!topOfStack.isOpenParen())
    {
    postfixExpression.add(topOfStack);
    operatorStack.pop();
    topOfStack = operatorStack.top();
    }
    //and then discard the open paren
    operatorStack.pop();
    }
    //If it is an operator ...
    else if (nextToken.isOperator())
    {
    // get the precedence of this token
    int tokenPrecedence = nextToken.getPrecedence();

    // If stack is empty, push nextToken into stack
    if (operatorStack.isEmpty())
    operatorStack.push(nextToken);
    else
    {
    //Get the precedence of the top of the stack
    topOfStack = operatorStack.top();

    //If the top of stack is an open parenthesis push nextToken
    if (topOfStack.isOpenParen())
    operatorStack.push(nextToken);
    else
    {
    //Get the precedence of the top of stack
    int stackPrecedence = topOfStack.getPrecedence();

    //if nextToken's precedence is > that of top of stack's
    //push next token into stack
    if (tokenPrecedence > stackPrecedence)
    operatorStack.push(nextToken);
    else
    {
    //Keep pulling operators out of stack and appending
    //them to postfix, as long all all these conditions are true
    while ((tokenPrecedence <= stackPrecedence) &&
    (!topOfStack.isOpenParen()) &&
    (!operatorStack.isEmpty()))
    {
    topOfStack = operatorStack.pop();
    postfixExpression.add(topOfStack);
    if (!operatorStack.isEmpty())
    {
    topOfStack = operatorStack.top();
    stackPrecedence = topOfStack.getPrecedence();
    }
    }

    //At the end push nextToken into Stack
    operatorStack.push(nextToken);
    }
    }
    }
    }

    else
    {
    System.out.println
    ("Illegal String in InfixToPostfixConverter");
    break;
    }
    }
    //At the end of the infix expression: pull all the operators
    //out of the stack and append them to postfix
    while (!operatorStack.isEmpty())
    {
    topOfStack = operatorStack.pop();
    postfixExpression.add(topOfStack);
    }
    }
    /**
    * Retriever method: returns the current postfix expression
    */
    public Expression getPostfix()
    {
    return postfixExpression;
    }

    }




    //-----------------------------------------------------------------
    package expeval;
    import stack.*;
    import java.util.*;

    /**
    * Evaluates postfix expression
    *
    * @author Alex Menz
    * @version 2013
    */
    public class PostfixEvaluator
    {
    //Input expression
    private Expression postfixExpression;
    private int valueOfExpression;
    private final int MAXSTACKSIZE = 100;

    /**
    * Constructor: assigns parameter to the instance variable
    */
    public PostfixEvaluator(Expression postfix)
    {
    postfixExpression = postfix;
    }

    /**
    * Evaluates the postfixExpression
    */
    public int eval()
    {
    //Starts with an empty operand stack
    ArrayStack<Token> operandStack = new ArrayStack<Token>(MAXSTACKSIZE);

    //Temp variable
    Token nextToken;
    ArrayList<Token> postfix = postfixExpression.getExpression();
    //Main Loop: Parse the postfix expression
    for (int k = 0; k < postfix.size(); k++)
    {
    //Get the next token from postfix
    nextToken = postfix.get(k);

    //If it is an operand, push it into stack
    if (nextToken.isOperand())
    {
    operandStack.push(nextToken);
    //System.out.println(operandStack);
    }
    //If it is an operator,
    else if (nextToken.isOperator())
    {
    //Get two operands out of the stack
    if (operandStack.isEmpty())
    {
    System.out.println("Error in PostfixEvaluator.eval() "+
    "-- Input expression was probably wrong");
    return Integer.MIN_VALUE;
    }
    Token operand2 = operandStack.pop();

    if (operandStack.isEmpty())
    {
    System.out.println("Error in PostfixEvaluator.eval() "+
    "-- Input expression was probably wrong");
    return Integer.MIN_VALUE;
    }
    Token operand1 = operandStack.pop();

    //Perform the operation
    Token result = calculate(nextToken, operand1, operand2);

    //Push the result back into the stack
    operandStack.push(result);
    //System.out.println(operandStack);
    }
    }

    //At the end, if only one element is left in the stack
    if (operandStack.isEmpty())
    {
    System.out.println("Error in PostfixEvaluator.eval() "+
    "-- Input expression was probably wrong");
    return Integer.MIN_VALUE;
    }

    //Get the operand out of the stack, and convert it into
    //an integer
    Token topToken = operandStack.pop();
    valueOfExpression = Integer.parseInt(topToken.getBody());

    if (operandStack.isEmpty())
    return valueOfExpression;
    else
    {
    System.out.println("Error in PostfixEvaluator.eval() "+
    "-- Input expression was probably wrong");
    return Integer.MIN_VALUE;
    }

    }

    /**
    * Performs an arithmetic operation
    */
    private Token calculate(Token opr, Token opd1, Token opd2)
    {
    // Get the first char from opr, it is the operator: +, -, ...
    char ch = opr.getBody().charAt(0);

    //Get the two operands by converting from String to int
    int op1 = Integer.parseInt(opd1.getBody());
    int op2 = Integer.parseInt(opd2.getBody());

    //Default return value, in case an error occurs
    int res = Integer.MAX_VALUE;


    if (ch == '<')
    {
    ch = opr.getBody().charAt(0);
    if (ch == '=') //<= symbol
    {
    if (op1 < op2 || op1 == op2)
    {
    return new Token(""+1);
    }
    }
    else //generic < symbol
    {
    if(op1 < op2)
    {
    return new Token(""+1);
    }
    }
    return new Token(""+0);
    }
    else if (ch == '>')
    {
    ch = opr.getBody().charAt(0);
    if (ch == '=') //>= symbol
    {
    if (op1 > op2 || op1 == op2)
    return new Token(""+1);
    }
    else //generic > symbol
    {
    if(op1 > op2)
    return new Token(""+1);
    }
    return new Token(""+0);
    }
    else if (ch == '=')
    {
    ch = opr.getBody().charAt(1);
    if (ch == '=') //== symbol
    {
    if (op1 == op2)
    return new Token(""+1);
    }
    return new Token(""+0);
    }
    else if (ch == '!')
    {
    ch = opr.getBody().charAt(1);
    if (ch == '=') //!= symbol
    {
    if (op1 != op2)
    return new Token(""+1);
    }
    return new Token(""+0);
    }
    else if (ch == '|')
    {
    ch = opr.getBody().charAt(1);
    if (ch == '|') //|| symbol
    {
    if ((op1 != 0) || (op2 != 0)) //if one of the numbers isn't 0
    return new Token(""+1);
    }
    return new Token(""+0);
    }
    else if (ch == '&')
    {
    ch = opr.getBody().charAt(1);
    if (ch == '&') //&& symbol
    {
    if ((op1 != 0) && (op2 != 0)) //if one of the numbers isn't 0
    return new Token(""+1);
    }
    return new Token(""+0);
    }

    //Perform the operation, and set a value for res
    switch (ch)
    {
    case '+' : res = op1+op2;break;
    case '-' : res = op1-op2;break;
    case '*' : res = op1*op2;break;
    case '/' : if (op2 != 0)
    res = op1/op2;
    else
    System.out.println("Division by zero error in"+
    " PostfixEvaluator.calculate().");
    break;
    case '%' : if (op2 != 0)
    res = op1%op2;
    else
    System.out.println("Division by zero error in"+
    " PostfixEvaluator.calculate().");
    break;
    default: System.out.println("Illegal Operator in "+
    "PostfixEvaluator.calculate()");
    }

    //Convert res into a Token and return it.
    return new Token(""+res);
    }
    }

    package expeval;


    /**
    * Represents a token in an expression. Just provides some
    * static methods
    *
    * @author Alex Menz
    * @version (2013)
    */
    public class Token
    {
    //-------------------------------------------------------------
    //It classifies the following as "OPERATORS". If you need more,
    //you have to change this
    private final static String[] validOperators =
    {"<", "<=", ">", ">=", "==", "!=", "||", "&&", "+","-","*","/","%"};

    //-------------------------------------------------------------
    private String body;

    //-------------------------------------------------------------
    private final static char OPENPAREN = '(';
    private final static char CLOSEDPAREN = ')';


    //-------------------------------------------------------------
    public Token(String tok)
    {
    body = tok;
    }

    //-------------------------------------------------------------
    public String getBody()
    {
    return body;
    }
    //-------------------------------------------------------------
    /**
    * Takes a String argument and checks if the first
    * char (i.e. charAt(0)) is an operator. The string
    * of valid operators is defined above.
    */
    public boolean isOperator()
    {
    for (int i = 0; i < validOperators.length; i++)
    if (validOperators[i].equals(body))
    return true;
    return false;
    }

    //-------------------------------------------------------------
    /**
    * Is the first char of the arg an open Parenthesis?
    */
    public boolean isOpenParen()
    {
    char ch = body.charAt(0);
    return (ch == OPENPAREN);
    }

    //-------------------------------------------------------------
    /**
    * Is the first char of the arg an close Parenthesis?
    */
    public boolean isClosedParen()
    {
    char ch = body.charAt(0);
    return (ch == CLOSEDPAREN);
    }

    //-------------------------------------------------------------
    public boolean isOperand()
    {
    return (! (( isOperator()
    || isOpenParen()
    || isClosedParen()
    )));
    }

    //-------------------------------------------------------------
    /**
    * Defines the precedence values for some operators.
    */
    public int getPrecedence()
    {
    if (body.equals("<")|| body.equals("<=")|| body.equals(">")|| body.equals(">="))
    return 1;
    else if (body.equals("==")|| body.equals("!="))
    return 2;
    else if (body.equals("||"))
    return 3;
    else if (body.equals("&&"))
    return 4;
    else if (body.equals("+") ||body.equals("-"))
    return 5;
    else if (body.equals("*") ||body.equals("/") || body.equals("%"))
    return 6;
    return -1;
    }

    public String toString()
    {
    return body;
    }

    }

    package stack;

    import java.util.*;
    /**
    * Implementation of a stack using an ArrayList to hold the
    * elements of the stack
    * @author Alex Menz
    *
    * @param <T>
    */
    public class ArrayListStack<T> implements IStack<T>
    {
    //--------------------------------------------------
    // Body of the stack is held in an ArrayList
    private ArrayList<T> stackBody;

    //--------------------------------------------------
    /**
    * Constructor: Instantiates the body
    */
    public ArrayListStack()
    {
    stackBody = new ArrayList<T>();
    }
    //--------------------------------------------------
    /**
    * Test for emptiness: size == 0 means stack is empty
    */
    public boolean isEmpty()
    {
    return (stackBody.size() == 0);
    }
    //--------------------------------------------------
    /**
    * Insert a new item at the top of the stack
    */
    public void push(T item)
    {
    stackBody.add(item);
    }
    //--------------------------------------------------
    /**
    * Delete the top-most element of the stack
    * Report error and return null if stack is empty
    */
    public T pop()
    {
    if (isEmpty())
    {
    System.out.println("Error in ArrayStack.pop() – Stack Empty ");
    return null;
    }
    else
    {
    T topElement = stackBody.get(stackBody.size()-1);
    stackBody.remove(stackBody.size()-1);
    return topElement;
    }
    }
    //--------------------------------------------------
    /**
    * Fetch the top-most element of the stack without
    * removing it. Report error and return null if stack
    * is empty
    */
    public T top()
    {
    if (isEmpty())
    {
    System.out.println("Error in ArrayStack.top() – Stack Empty ");
    return null;
    }
    else
    {
    T topElement = stackBody.get(stackBody.size()-1);
    return topElement;
    }
    }

    }

    package stack;
    /**
    * File: ArrayStack.java
    * This implements the IStack interface using an array to
    * represent the body of the stack. The user decides the
    * maximum size of the stack at the time of instantiation.
    *
    * @author Alex Menz
    *
    * @param <T>
    */
    public class ArrayStack<T> implements IStack<T>
    {
    private T stackBody[];
    private int top;
    //--------------------------------------------------------
    /**
    * Constructor
    * Size is passed by user as a parameter
    */
    public ArrayStack(int size)
    {
    // Java does not permit creation of generic arrays!!
    // So, we can’t do this.
    // stackBody = new T [size];
    // Instead we create an object array and cast it to T.
    // You get a warning. Ignore it.
    stackBody = (T[])new Object [size];
    top = -1;
    }
    //--------------------------------------------------------
    /**
    * Test for emptiness: variable top represents the location
    * of the top-most element of the stack. top = -1 implies
    * empty stack
    */
    public boolean isEmpty()
    {
    return (top == -1);
    }
    //--------------------------------------------------------
    /**
    * Insert a new item into stack.
    * First make sure that there is room. Increment top and
    * store new item at the new top location
    * If there is no room, report error. Nothing is pushed.
    */
    public void push(T item)
    {
    if (top < stackBody.length-1)
    {
    top++;
    stackBody[top] = item;
    }
    else
    {
    System.out.println("Error in ArrayStack.push() – Stack Full ");
    }
    }
    //--------------------------------------------------------
    /**
    * Remove the top element of the stack. Report error if
    * stack is empty,
    */
    public T pop()
    {
    if (isEmpty())
    {
    System.out.println("Error in ArrayStack.pop() – Stack Empty ");
    return null;
    }
    else
    {
    T topElement = stackBody[top];
    top--;
    return topElement;
    }
    }
    //--------------------------------------------------------
    /**
    * Fetch the top-most element of the stack without
    * removing it. Report error if stack is empty and
    * return null.
    */
    public T top()
    {
    if (isEmpty())
    {
    System.out.println("Error in ArrayStack.top() – Stack Empty ");
    return null;
    }
    else
    {
    T topElement = stackBody[top];
    return topElement;
    }
    }

    }

    //----------------------------------------------------------------
    // NOTE: There are two packages here: stack and expression
    // Create these packages in your csc205 project in Eclipse
    // and copy and paste the interfaces and classes one by one
    //----------------------------------------------------------------
    package stack;
    //----------------------------------------------------------------
    /**
    * Interface defines a generic stack
    * @author Alex Menz
    *
    * @param <T>
    */
    public interface IStack<T>
    {
    public boolean isEmpty();
    public void push(T item);
    public T pop();
    public T top();
    }

  2. #2
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default Re: Need GUI Help everything else works

    First, please use [code] tags [/code] when posting code in order to retain formatting.
    Second, you haven't actually asked a question.
    Third, that's a lot of code to expect people to look at...I'm sure you can narrow down your problem.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. How this works
    By snowed in forum New To Java
    Replies: 2
    Last Post: 04-02-2012, 02:08 AM
  2. toCharArray() How it works ?
    By Austin in forum New To Java
    Replies: 10
    Last Post: 08-05-2011, 09:19 AM
  3. How JVM works in linux box ?
    By vinothjava in forum Advanced Java
    Replies: 14
    Last Post: 05-06-2011, 12:02 PM
  4. Anyone know how GroupLayout works?
    By ProgrammingPup in forum Advanced Java
    Replies: 5
    Last Post: 12-01-2009, 11:12 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •