开发者

'SImple' 2 class Java calculator doesn't accept inputs or do calculations

开发者 https://www.devze.com 2022-12-24 10:32 出处:网络
I\'m trying to get a two class java calculator working (new to java) but so far i\'m having no success.the two classes are outlined below, calcFrame is for the interface and calEngine should do the ac

I'm trying to get a two class java calculator working (new to java) but so far i'm having no success. the two classes are outlined below, calcFrame is for the interface and calEngine should do the actual calculations but i can't get them to talk to one another. I'd really appreciate any assistance on same. Thanks.

CalcFrame Code:

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


/**
*A Class that operates as the f开发者_高级运维ramework for a calculator. 
*No calculations are performed in this section
*/
public class CalcFrame implements ActionListener {

private CalcEngine calc;

private JFrame frame;
private JTextField display;
private JLabel status;

/**
 * Constructor for objects of class GridLayoutExample
 */
public CalcFrame()
{
    makeFrame();
    //calc = engine;
}



/**
 * This allows you to quit the calculator.
 */

// Alows the class to quit.
private void quit()
{
    System.exit(0);


}

// Calls the dialog frame with the information about the project.
private void showAbout()
{
    JOptionPane.showMessageDialog(frame, 
                "Group Project",
                "About Calculator Group Project", 
                JOptionPane.INFORMATION_MESSAGE);
}



private void makeFrame()
{
    frame = new JFrame("Group Project Calculator");
    makeMenuBar(frame);

    JPanel contentPane = (JPanel)frame.getContentPane();
    contentPane.setLayout(new BorderLayout(8, 8));
    contentPane.setBorder(new EmptyBorder( 10, 10, 10, 10));



    /**
 * Insert a text field
 */
    display = new JTextField();
    contentPane.add(display, BorderLayout.NORTH);

    //Container contentPane = frame.getContentPane();
    contentPane.setLayout(new GridLayout(4, 4));
    JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
    contentPane.add(new JButton("1"));
    contentPane.add(new JButton("2"));
    contentPane.add(new JButton("3"));
    contentPane.add(new JButton("4"));
    contentPane.add(new JButton("5"));
    contentPane.add(new JButton("6"));
    contentPane.add(new JButton("7"));
    contentPane.add(new JButton("8"));
    contentPane.add(new JButton("9"));
    contentPane.add(new JButton("0"));
    contentPane.add(new JButton("+"));
    contentPane.add(new JButton("-"));
    contentPane.add(new JButton("/"));
    contentPane.add(new JButton("*"));
    contentPane.add(new JButton("="));
    contentPane.add(new JButton("C"));

    contentPane.add(buttonPanel, BorderLayout.CENTER);

    //status = new JLabel(calc.getAuthor());
    //contentPane.add(status, BorderLayout.SOUTH);

    frame.pack();
    frame.setVisible(true);
}

/**
 * Create the main frame's menu bar.
 * The frame that the menu bar should be added to.
 */
private void makeMenuBar(JFrame frame)
{
    final int SHORTCUT_MASK =
        Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();


    JMenuBar menubar = new JMenuBar();
    frame.setJMenuBar(menubar);

    JMenu menu;
    JMenuItem item;

    // create the File menu
    menu = new JMenu("File");
    menubar.add(menu);

    // create the Quit menu with a shortcut "Q" key.
     item = new JMenuItem("Quit");
        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
        item.addActionListener(new ActionListener() {
                           public void actionPerformed(ActionEvent e) { quit(); }
                       });
    menu.add(item);

    // Adds an about menu.
    menu = new JMenu("About");
    menubar.add(menu);

    // Displays 
    item = new JMenuItem("Calculator Project");
        item.addActionListener(new ActionListener() {
                           public void actionPerformed(ActionEvent e) { showAbout(); }
                       });
    menu.add(item);

}


/**
 * An interface action has been performed.
 * Find out what it was and handle it.
 * @param event The event that has occured.
 */
public void actionPerformed(ActionEvent event)
{
    String command = event.getActionCommand();

    if(command.equals("0") ||
       command.equals("1") ||
       command.equals("2") ||
       command.equals("3") ||
       command.equals("4") ||
       command.equals("5") ||
       command.equals("6") ||
       command.equals("7") ||
       command.equals("8") ||
       command.equals("9")) {
        int number = Integer.parseInt(command);
        calc.numberPressed(number);
    }
    else if(command.equals("+")) {
        calc.plus();
    }
    else if(command.equals("-")) {
        calc.minus();
    }
    else if(command.equals("=")) {
        calc.equals();
    }
    else if(command.equals("C")) {
        calc.clear();
    }
    else if(command.equals("?")) {

    }
    // else unknown command.

    redisplay();
}

/**
 * Update the interface display to show the current value of the 
 * calculator.
 */
private void redisplay()
{
    display.setText("" + calc.getDisplayValue());
}

/**
 * Toggle the info display in the calculator's status area between the
 * author and version information.
 */

}

CalcEngine:

public class CalcEngine
{
// The calculator's state is maintained in three fields:
//     buildingDisplayValue, haveLeftOperand, and lastOperator.


// The current value (to be) shown in the display.
private int displayValue;
// The value of an existing left operand.
private int leftOperand;

/**
 * Create a CalcEngine.
 */
public CalcEngine()
{
    clear();
}


public int getDisplayValue()
{
    return displayValue;
}

/**
 * A number button was pressed.
 * Either start a new operand, or incorporate this number as
 * the least significant digit of an existing one.
 * @param number The number pressed on the calculator.
 */
public void numberPressed(int number)
{
    if(buildingDisplayValue) {
        // Incorporate this digit.
        displayValue = displayValue*10 + number;
    }
    else {
        // Start building a new number.
        displayValue = number;
        buildingDisplayValue = true;
    }
}

/**
 * The 'plus' button was pressed. 
 */
public void plus()
{
    applyOperator('+');
}

/**
 * The 'minus' button was pressed.
 */
public void minus()
{
    applyOperator('-');
}

/**
 * The '=' button was pressed.
 */
public void equals()
{
    // This should completes the building of a second operand,
    // so ensure that we really have a left operand, an operator
    // and a right operand.
    if(haveLeftOperand &&
            lastOperator != '?' &&
            buildingDisplayValue) {
        calculateResult();
        lastOperator = '?';
        buildingDisplayValue = false;
    }
    else {
        keySequenceError();
    }
}

/**
 * The 'C' (clear) button was pressed.
 * Reset everything to a starting state.
 */
public void clear()
{
    lastOperator = '?';
    haveLeftOperand = false;
    buildingDisplayValue = false;
    displayValue = 0;
}

/**
 * @return The title of this calculation engine.
 */
public String getTitle()
{
    return "Java Calculator";
}

/**
 * @return The author of this engine.
 */
public String getAuthor()
{
    return "David J. Barnes and Michael Kolling";
}

/**
 * @return The version number of this engine.
 */
public String getVersion()
{
   return "Version 1.0";
}

/**
 * Combine leftOperand, lastOperator, and the
 * current display value.
 * The result becomes both the leftOperand and
 * the new display value.
 */
private void calculateResult()
{
    switch(lastOperator) {
        case '+':
            displayValue = leftOperand + displayValue;
            haveLeftOperand = true;
            leftOperand = displayValue;
            break;
        case '-':
            displayValue = leftOperand - displayValue;
            haveLeftOperand = true;
            leftOperand = displayValue;
            break;
        default:
            keySequenceError();
            break;
    }
}

/**
 * Apply an operator.
 * @param operator The operator to apply.
 */
private void applyOperator(char operator)
{
    // If we are not in the process of building a new operand
    // then it is an error, unless we have just calculated a
    // result using '='.
    if(!buildingDisplayValue &&
                !(haveLeftOperand && lastOperator == '?')) {
        keySequenceError();
        return;
    }

    if(lastOperator != '?') {
        // First apply the previous operator.
        calculateResult();
    }
    else {
        // The displayValue now becomes the left operand of this
        // new operator.
        haveLeftOperand = true;
        leftOperand = displayValue;
    }
    lastOperator = operator;
    buildingDisplayValue = false;
}

/**
 * Report an error in the sequence of keys that was pressed.
 */
private void keySequenceError()
{
    System.out.println("A key sequence error has occurred.");
    // Reset everything.
    clear();
}

}


The 'engine' is not initialized'

public CalcFrame() {
    makeFrame();
    calc = new CalcEngine();
}

AND:
You should attach a listener to the buttons, so the actionPerformed() is called when they are clicked

JButton button = new JButton("1");
button.addActionListener(this);
contentPane.add(button);

This should be done for each button, so it's best to put the buttons in a list first:

JPanel buttonPanel = new JPanel(new GridLayout(4, 4));

List<JButton> buttons = new ArrayList<JButton>();

buttons.add(new JButton("1"));
buttons.add(new JButton("2"));
buttons.add(new JButton("3"));
buttons.add(new JButton("4"));
buttons.add(new JButton("5"));
buttons.add(new JButton("6"));
buttons.add(new JButton("7"));
buttons.add(new JButton("8"));
buttons.add(new JButton("9"));
buttons.add(new JButton("0"));
buttons.add(new JButton("+"));
buttons.add(new JButton("-"));
buttons.add(new JButton("/"));
buttons.add(new JButton("*"));
buttons.add(new JButton("="));
buttons.add(new JButton("C"));




for(JButton button : buttons){
     buttonPanel.add(button);
     button.addActionListener(this);
 }

 contentPane.add(buttonPanel, BorderLayout.CENTER);

By the way, you are missing the } else if (command.equals("*")) { part


You never add your framework class to your buttons as an ActionListener. Try changing the code where you add them to this:

JButton tmp = new JButton("1");
tmp.addActionListener(this);
contentPane.add(tmp);

You'll need to do it for each button.

Because you never add your CalcFrame class to the buttons as their ActionListener they have nothing to call when they are pressed. Your actionPerformed function never gets called. You have to tell the buttons what ActionListener to use. Then when they are pressed, they will cycle through their list of ActionListeners and call each one's actionPerformed function.

0

精彩评论

暂无评论...
验证码 换一张
取 消