Java Stack Calculator | RPN Conversion Help for Beginners

  • Context: Comp Sci 
  • Thread starter Thread starter ali11
  • Start date Start date
  • Tags Tags
    Java
Click For Summary

Discussion Overview

The discussion revolves around the implementation of a Reverse Polish Notation (RPN) calculator in Java, focusing on how to effectively utilize a stack data structure for operations. Participants are exploring the mechanics of RPN, including how to handle user input and perform calculations based on stack operations.

Discussion Character

  • Exploratory
  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant seeks assistance in modifying a simple calculator to function as an RPN calculator, specifically asking about the use of the pop method in stack operations.
  • Another participant questions the fundamental operations of an RPN calculator, asking for clarification on how addition, subtraction, multiplication, division, sign changes, and squaring should be executed.
  • A participant provides an example of how to subtract two numbers using RPN, illustrating the sequence of inputs and stack operations.
  • Another participant elaborates on the expected behavior of the program when performing operations, detailing the steps of pushing numbers onto the stack and popping them for calculations.

Areas of Agreement / Disagreement

There is no consensus yet on the specific implementation details of the RPN calculator, as participants are still discussing the mechanics and expected behavior of the calculator operations.

Contextual Notes

Participants have not yet resolved how to handle various operations in the context of RPN, and there may be assumptions about user input and stack management that are not fully articulated.

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 ·
Replies
1
Views
2K
  • · Replies 9 ·
Replies
9
Views
4K
  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 14 ·
Replies
14
Views
6K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 10 ·
Replies
10
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K