3

When trying to call on a method from another class my method as a error at

private class equalsButton implements ActionListener {

    // makes the equals button listener
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("=");
        InfixToPostfixParens.convert(operator); // Line with error
    }
}

Saying Non Static String cannot be referenced from a static context. The variable isn't static but I still get this problem any ideas?

The Bulk of my main program as it stands now (Sorry for the sloppy coding in places)

/**
 * Graphics of the calculator
 * 
 * @author Collin Blake
 * @version (2-28-11)
 */
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleCalculator extends JFrame {

    JTextField textField;
    String operator = "";

    public SimpleCalculator() {
        setTitle("Simple Calculator"); // makes the window for the calculator
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(0, 1));
        JPanel topPanel = new JPanel(); // Initilaized for the text window
        topPanel.setLayout(new GridLayout());
        textField = new JTextField(10);
        textField.addActionListener(new NumEntered());
        topPanel.add(textField);
        add(topPanel);
        JPanel centerPanel = new JPanel(); // center panel initilaized
        centerPanel.setLayout(new GridLayout(0, 4));
        JButton oneButton = new JButton("1"); // initilaized values for each
                                                // button in their menus
        JButton twoButton = new JButton("2");
        JButton threeButton = new JButton("3");
        JButton plusButton = new JButton("+");
        JButton fourButton = new JButton("4");
        JButton fiveButton = new JButton("5");
        JButton sixButton = new JButton("6");
        JButton minusButton = new JButton("-");
        JButton sevenButton = new JButton("7");
        JButton eightButton = new JButton("8");
        JButton nineButton = new JButton("9");
        JButton timesButton = new JButton("*");
        JButton zeroButton = new JButton("0");
        JButton decimalButton = new JButton(".");
        JButton powerButton = new JButton("^");
        JButton divideButton = new JButton("/");
        JButton LParButton = new JButton("(");
        JButton RParButton = new JButton(")");
        JButton equalsButton = new JButton("="); // creates equals button
        JButton allClearButton = new JButton("AC");
        oneButton.addActionListener(new oneButton()); // initilaized values for
                                                        // each button's
                                                        // actionlistener
        twoButton.addActionListener(new twoButton());
        threeButton.addActionListener(new threeButton());
        plusButton.addActionListener(new plusButton());
        fourButton.addActionListener(new fourButton());
        fiveButton.addActionListener(new fiveButton());
        sixButton.addActionListener(new sixButton());
        minusButton.addActionListener(new minusButton());
        sevenButton.addActionListener(new sevenButton());
        eightButton.addActionListener(new eightButton());
        nineButton.addActionListener(new nineButton());
        timesButton.addActionListener(new timesButton());
        zeroButton.addActionListener(new zeroButton());
        decimalButton.addActionListener(new decimalButton());
        powerButton.addActionListener(new powerButton());
        divideButton.addActionListener(new divideButton());
        LParButton.addActionListener(new LParButton());
        RParButton.addActionListener(new RParButton());
        equalsButton.addActionListener(new equalsButton()); // creates action
                                                            // listener for
                                                            // equals
        allClearButton.addActionListener(new allClearButton());
        centerPanel.add(oneButton); // Adds the buttons to the sub panel
        centerPanel.add(twoButton);
        centerPanel.add(threeButton);
        centerPanel.add(plusButton);
        centerPanel.add(fourButton);
        centerPanel.add(fiveButton);
        centerPanel.add(sixButton);
        centerPanel.add(minusButton);
        centerPanel.add(sevenButton);
        centerPanel.add(eightButton);
        centerPanel.add(nineButton);
        centerPanel.add(timesButton);
        centerPanel.add(zeroButton);
        centerPanel.add(decimalButton);
        centerPanel.add(powerButton);
        centerPanel.add(divideButton);
        centerPanel.add(LParButton);
        centerPanel.add(RParButton);
        centerPanel.add(equalsButton);
        centerPanel.add(allClearButton);
        add(centerPanel); // Creates the panel with buttons
        pack();
        setLocationRelativeTo(null);
    }

    private class NumEntered implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            // do nothing
        }
    }

    private class oneButton implements ActionListener {

        // makes the one button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("1");
            operator += "1";
            textField.setText(operator);
        }
    }

    private class twoButton implements ActionListener {

        // makes the two button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("2");
            operator += "2";
            textField.setText(operator);
        }
    }

    private class threeButton implements ActionListener {

        // makes the three button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("3");
            operator += "3";
            textField.setText(operator);
        }
    }

    private class fourButton implements ActionListener {

        // makes the four button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("4");
            operator += "4";
            textField.setText(operator);
        }
    }

    private class fiveButton implements ActionListener {

        // makes the five button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("5");
            operator += "5";
            textField.setText(operator);
        }
    }

    private class sixButton implements ActionListener {

        // makes the six button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("6");
            operator += "6";
            textField.setText(operator);
        }
    }

    private class sevenButton implements ActionListener {

        // makes the seven button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("7");
            operator += "7";
            textField.setText(operator);
        }
    }

    private class eightButton implements ActionListener {

        // makes the eight button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("8");
            operator += "8";
            textField.setText(operator);
        }
    }

    private class nineButton implements ActionListener {

        // makes the nine button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("9");
            operator += "9";
            textField.setText(operator);
        }
    }

    private class zeroButton implements ActionListener {

        // makes the zerobutton listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("0");
            operator += "0";
            textField.setText(operator);
        }
    }

    private class plusButton implements ActionListener {

        // makes the plus button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("+");
            operator += "+";
            textField.setText(operator);
        }
    }

    private class minusButton implements ActionListener {

        // makes the minus button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("-");
            operator += "-";
            textField.setText(operator);
        }
    }

    private class timesButton implements ActionListener {

        // makes the times button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("*");
            operator += "*";
            textField.setText(operator);
        }
    }

    private class divideButton implements ActionListener {

        // makes the divide button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("/");
            operator += "/";
            textField.setText(operator);
        }
    }

    private class allClearButton implements ActionListener {

        // makes the all clear button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("AC");
            operator = "";
            textField.setText(operator);
        }
    }

    private class decimalButton implements ActionListener {

        // makes the decimal button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(".");
            operator += ".";
            textField.setText(operator);
        }
    }

    private class equalsButton implements ActionListener {

        // makes the equals button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("=");
            InfixToPostfixParens.convert(operator);
        }
    }

    private class LParButton implements ActionListener {

        // makes the ( button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("(");
            operator += "(";
            textField.setText(operator);
        }
    }

    private class RParButton implements ActionListener {

        // makes the ) button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(")");
            operator += ")";
            textField.setText(operator);
        }
    }

    private class powerButton implements ActionListener {

        // makes the ^ button listener
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("^");
            operator += "^";
            textField.setText(operator);
        }
    }
}

The code for the InfixToPostfixParens

import java.util.Stack;
import java.util.EmptyStackException;
import java.util.regex.Pattern;
import java.util.Scanner;

/**
 * Translates an infix expression with parentheses to a postfix expression.
 * 
 * @author Koffman & Wolfgang
 */
public class InfixToPostfixParens {

    // Nested Class
    /** Class to report a syntax error. */
    public static class SyntaxErrorException extends Exception {

        /**
         * Construct a SyntaxErrorException with the specified message.
         * 
         * @param message
         *            The message
         */
        SyntaxErrorException(String message) {
            super(message);
        }
    }

    // Data Fields
    /** The operator stack */
    private Stack<Character> operatorStack;
    /** The operators */
    private static final String OPERATORS = "-+*/()";
    /**
     * The Pattern to extract tokens A token is either a string of digits (\d+)
     * or a JavaIdentifier or an operator
     */
    private static final Pattern pattern = Pattern.compile("\\d+\\.\\d*|\\d+|"
            + "\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*" + "|["
            + OPERATORS + "]");
    /** The precedence of the operators, matches order of OPERATORS. */
    private static final int[] PRECEDENCE = { 1, 1, 2, 2, -1, -1 };
    /** The postfix string */
    private StringBuilder postfix;

    /**
     * Convert a string from infix to postfix.
     * 
     * @param infix
     *            The infix expression
     * @throws SyntaxErrorException
     */
    public String convert(String infix) throws SyntaxErrorException {
        operatorStack = new Stack<Character>();
        postfix = new StringBuilder();
        Scanner scan = new Scanner(infix);
        try {
            // Process each token in the infix string.
            String nextToken;
            while ((nextToken = scan.findInLine(pattern)) != null) {
                char firstChar = nextToken.charAt(0);
                // Is it an operand?
                if (Character.isJavaIdentifierStart(firstChar)
                        || Character.isDigit(firstChar)) {
                    postfix.append(nextToken);
                    postfix.append(' ');
                } // Is it an operator?
                else if (isOperator(firstChar)) {
                    processOperator(firstChar);
                } else {
                    throw new SyntaxErrorException(
                            "Unexpected Character Encountered: " + firstChar);
                }
            } // End while.
                // Pop any remaining operators
                // and append them to postfix.
            while (!operatorStack.empty()) {
                char op = operatorStack.pop();
                // Any '(' on the stack is not matched.
                if (op == '(') {
                    throw new SyntaxErrorException(
                            "Unmatched opening parenthesis");
                }
                postfix.append(op);
                postfix.append(' ');
            }
            // assert: Stack is empty, return result.
            return postfix.toString();
        } catch (EmptyStackException ex) {
            throw new SyntaxErrorException("Syntax Error: The stack is empty");
        }
    }

    /**
     * Method to process operators.
     * 
     * @param op
     *            The operator
     * @throws EmptyStackException
     */
    private void processOperator(char op) {
        if (operatorStack.empty() || op == '(') {
            operatorStack.push(op);
        } else {
            // Peek the operator stack and
            // let topOp be the top operator.
            char topOp = operatorStack.peek();
            if (precedence(op) > precedence(topOp)) {
                operatorStack.push(op);
            } else {
                // Pop all stacked operators with equal
                // or higher precedence than op.
                while (!operatorStack.empty()
                        && precedence(op) <= precedence(topOp)) {
                    operatorStack.pop();
                    if (topOp == '(') {
                        // Matching '(' popped - exit loop.
                        break;
                    }
                    postfix.append(topOp);
                    postfix.append(' ');
                    if (!operatorStack.empty()) {
                        // Reset topOp.
                        topOp = operatorStack.peek();
                    }
                }
                // assert: Operator stack is empty or
                // current operator precedence >
                // top of stack operator precedence.
                if (op != ')') {
                    operatorStack.push(op);
                }
            }
        }
    }

    /**
     * Determine whether a character is an operator.
     * 
     * @param ch
     *            The character to be tested
     * @return true if ch is an operator
     */
    private boolean isOperator(char ch) {
        return OPERATORS.indexOf(ch) != -1;
    }

    /**
     * Determine the precedence of an operator.
     * 
     * @param op
     *            The operator
     * @return the precedence
     */
    private int precedence(char op) {
        return PRECEDENCE[OPERATORS.indexOf(op)];
    }
}
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
Collin
  • 33
  • 1
  • 4
  • can you post some more details? Which line do you get the error exactly? Also give some details on how `Operator` is declared – Nivas Mar 01 '11 at 09:20
  • 2
    I think you might need to give us more. I'm assuming that this class, "equalsButton" is an inner class. As such it should have access to the members in the containing class. I assume that Operator is a field declared in the containing class? Can you boil down to a simpler standalone example? – Tom Quarendon Mar 01 '11 at 09:23
  • I don't like the attitude in here. Much insight has been given towards resolving this, while downvotes are being handed out left and right and posts are consequently being deleted. In particular in respect to Nivas, who appears to have downvoted all three original answers. – Paul Lammertsma Mar 01 '11 at 09:32
  • Honestly I appreciate the comments first time asking for help here and I didn't want to start anything. Just trying to get help where I have been stuck at for the last 4 hours. – Collin Mar 01 '11 at 09:34
  • You should turn all those near identical inner classes into one class that takes the operator character as a parameter to the constructor. – Christoffer Hammarström Mar 01 '11 at 09:59
  • But they are only near identical. You then have to have a big lot of if-then-elses to decide what to do. Actually seems relatively sensible I think. – Tom Quarendon Mar 01 '11 at 10:04

1 Answers1

1

How does your code differ from the following (which compiles)?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Example1 {
    private String operator;

    private class equalsButton implements ActionListener {
        public void actionPerformed(ActionEvent e) {
           System.out.println("=");
           InfixToPostfixParens.convert(operator);
        }
    }
}

public class InfixToPostfixParens {
    public static void convert(String s) {
      // Do something useful
    }
}
Tom Quarendon
  • 5,625
  • 5
  • 23
  • 30
  • Here let me just post the bulk of my code seems to be too much confusion. – Collin Mar 01 '11 at 09:38
  • Compiles fine for me. Just copied and pasted it into eclipse, and it's fine. You sure the problem isn't in InfixToPostfixParens? How is that declared? Is InfixToPostfixParens.convert declared static? – Tom Quarendon Mar 01 '11 at 09:44
  • Well when I try to comply it with my Java it gets the error there saying the static problem do you want me to post the class I'm trying to use from InfixToPostfixParens? – Collin Mar 01 '11 at 09:45
  • The problem is that your InfixToPostfixParens.convert isn't static. So you're calling a non-static method with static syntax. The Eclipse compiler gives a sensible error here, and not "non-static reference to static string". Possibly you'll need to new up an InfoxToPostfixParens and then call convert on it, or maybe have a InfoxToPostfixParens as a member in your SimpleCalculator class, depending on how you've written the class and whether you can reuse instances etc. Haven't looked at the code thoroughly enough to tell. – Tom Quarendon Mar 01 '11 at 09:51
  • so maybe declaring the method as static or run new InfixToPostfixParens then run convert would be the two paths to go? – Collin Mar 01 '11 at 09:55
  • You can't declare InfixToPostfixParens.convert static as it relies on loads of member variables. Hence my comment that either you need to new up a InfixToPostfixParens inside equalsButton.actionPerformed and then call convert on it, or you need to have InfixToPostfixParens as a member of SimpleCalculator so that you can call convert on that instance. Without going into detail of what InfixToPostfixParens does, I can't give a best answer, but probably the first. – Tom Quarendon Mar 01 '11 at 10:00
  • by new up you mean declare new correct? (sorry not good with the phrases) – Collin Mar 01 '11 at 10:05
  • Yes, I mean InfixToPostfixParens p = new InfixToPostfixParen(); p.convert(operator);, or new InfixToPostfixParens().convert(operator); You'll then need to deal with the SyntaxErrorException that is thrown by convert, but I'll leave that as an exersize. – Tom Quarendon Mar 01 '11 at 10:20
  • 'new up' LOL. That should be added to the standard Java slang dictionary! Your InfixToPostfixParens sounds like a stateless utility class. If so you can probably declare the convert method static. If it does have state, then you might need to initialize it in the constructor or inject it as a dependency from elsewhere (i.e. Spring). – Adriaan Koster Mar 01 '11 at 10:51
  • The method can't be static, as the class has many member variables that store the state of the conversion. I'd suggest that "dependency injection" is too complicated. It's a "functor" class really -- i.e a single "function" that is split into several methods with state. The way it's coded seems fine. "dependency injection" seems overcomplicated for what this seems to be. – Tom Quarendon Mar 01 '11 at 11:11