Comp Sci Java Stack Calculator | RPN Conversion Help for Beginners

  • Thread starter Thread starter ali11
  • Start date Start date
  • Tags Tags
    Java
AI Thread Summary
The discussion focuses on converting a simple Java calculator into a Reverse Polish Notation (RPN) calculator using a stack. Participants emphasize the importance of correctly implementing the pop method to retrieve values from the stack for calculations. They explain that when adding, subtracting, multiplying, or dividing, the calculator should push numbers onto the stack and then pop them for operations. The sequence of user inputs and corresponding stack actions is outlined, illustrating how to handle operations like subtraction. Overall, the conversation provides guidance on the necessary steps to effectively implement RPN functionality in the calculator.
ali11
Messages
12
Reaction score
0
First i create simple claculator.but now I am trying to change it to RPN calculator by using stack.Can some one help me((especially where to use pop method) because I don't know a lot about stack.here is my codes so far.

Code:
import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;
import java.util.Scanner;


public class CalcGUIPanel extends JPanel
{



Stack s=new Stack();


//--\- Component referenced during execution

private JTextField displayField; // display result / input.

//--\- Variables representing state of the calculator

private boolean startNumber = true; // true: num key next

private int resultValue = 0; // result so far

private String previousOp = "="; // previous operation

//========================================= static (class) variables

private static final Font BIGGER_FONT =

new Font("monspaced", Font.PLAIN, 20);

//====================================================== constructor

public CalcGUIPanel()
{

//--\- Display field

displayField = new JTextField();


//--\- Clear button

JButton clearButton = new JButton("CLEAR");

clearButton.setFont(BIGGER_FONT);

clearButton.addActionListener(new ClearListener());

//--\- One listener for all numeric keys.

ActionListener numListener = new NumListener();

//--\- Layout numeric keys in a grid. Generate the buttons

// in a loop from the chars in a string.

String buttonOrder = "789456123 0 ";

JPanel buttonPanel = new JPanel(new GridLayout(5, 3));

for (int i = 0; i < buttonOrder.length(); i++) {

String keyTop = buttonOrder.substring(i, i+1);

if (keyTop.equals(" ")) {

buttonPanel.add(new JLabel(""));

} else {

JButton b = new JButton(keyTop);

b.addActionListener(numListener);
s.push("0");
s.push("1");
s.push("2");
s.push("3");
s.push("4");
s.push("5");
s.push("6");
s.push("7");
s.push("8");
s.push("9");

b.setFont(BIGGER_FONT);

buttonPanel.add(B);

}

}

//--\- One ActionListener to use for all operator buttons.

ActionListener opListener = new OpListener();

//--\- Create panel with gridlayout to hold operator buttons.

// Use array of button names to create buttons in a loop.

JPanel opPanel = new JPanel(new GridLayout(5, 1));

String[] opOrder = {"+", "-", "*", "/", "enter"};

for (int i = 0; i < opOrder.length; i++) {

JButton b = new JButton(opOrder[i]);

b.addActionListener(opListener);

s.push("+");
s.push("-");
s.push("*");
s.push("/");
s.push("enter");


b.setFont(BIGGER_FONT);

opPanel.add(B);

}

//--\- Layout the top-level panel.

this.setLayout(new BorderLayout());

this.add(displayField, BorderLayout.NORTH );

this.add(buttonPanel , BorderLayout.CENTER);

this.add(opPanel , BorderLayout.EAST );

this.add(clearButton , BorderLayout.SOUTH );

}//end constructor

//====================================================== action_clear

/*\* Called by Clear btn action listener and elsewhere.*/

private void action_clear() {

startNumber = true;

displayField.setText("0");

resultValue = 0;

previousOp = "=";

}

// inner listener class OpListener

/*\* Listener for all op buttons. \*/

class OpListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

// The calculator is always in one of two states.

// 1. A number must be entered \-\- this operator is wrong.

// 2. An operator must be entered \-\- we're ok.

{

startNumber = true; // Next thing must be a number

try {

// Get value from display field, convert, do prev op

// If this is the first op, \_previousOp will be =.

String displayText = displayField.getText();

int currentValue = Integer.parseInt(displayText);

if (previousOp.equals("=")) {

resultValue = currentValue;

} else if (previousOp.equals("+")) {

resultValue += currentValue;

} else if (previousOp.equals("-")) {

resultValue -= currentValue;

} else if (previousOp.equals("*")) {

resultValue *= currentValue;

} else if (previousOp.equals("/")) {

resultValue /= currentValue;

}

displayField.setText(""+resultValue);

} catch (NumberFormatException ex) {

action_clear();

displayField.setText("Error");

}

//--\- set \_previousOp for the next operator.

previousOp = e.getActionCommand();

}//endif \_startNumber

}//endmethod

}//end class

//////////////////////////////////// inner listener class ClearListener

// Action listener for numeric keys

class NumListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

String digit = e.getActionCommand(); // Get text from button

if (startNumber) {

// This is the first digit, clear field and set

displayField.setText(digit);

startNumber = false;

} else {

// Add this digit to the end of the display field

displayField.setText(displayField.getText() + digit);

}

}

}//end class

//inner listener class ClearListener

class ClearListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

action_clear();

}

}

}
 
Physics news on Phys.org
OK, so tell us what you know about how an RPN calculator should work.

What should happen if you want to add two numbers?
What should happen if you want to subtract two numbers?
What should happen if you want to multiply two numbers?
What should happen if you want to divide two numbers?
What should happen if you want to change the sign of a number?
What should happen if you want to square a number?
 
To subtract two numbers it should be like this
7
enter
1
-
 
OK, fine. Since your program is using a stack to implement an RPN calculator, here's what your program should do.
User: press 7 then press Enter.
User: press Enter key.
Program: push 7 onto stack.
User: press 1 then press Enter.
Program: push 1 onto stack.
User: press - key.
Program: pop top of stack (1), pop top of stack (7), calculate 7 - 1, display 6.

The other three arithmetic operations are similar.
 

Similar threads

Replies
1
Views
2K
Replies
9
Views
4K
Replies
2
Views
3K
Replies
3
Views
4K
Replies
1
Views
2K
Replies
9
Views
3K
Back
Top