Java Stack Calculator | RPN Conversion Help for Beginners

  • Comp Sci
  • Thread starter ali11
  • Start date
  • Tags
    Java
In summary: To change the sign of a number, the user would press the - key without entering a second number. To square a number, the user would enter the number, press the * key, and then press Enter. The program would pop the top of the stack (the number entered), multiply it by itself, and display the result. In summary, the conversation discusses the creation of an RPN calculator, which uses a stack to implement its functions. The program takes in user input through a GUI, and performs arithmetic operations such as addition, subtraction, multiplication, and division by popping and pushing numbers onto the stack. The program also allows for changing the sign of a number and squaring a number.
  • #1
ali11
12
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
  • #2
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?
 
  • #3
To subtract two numbers it should be like this
7
enter
1
-
 
  • #4
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.
 
  • #5


I would suggest seeking help from someone who is knowledgeable in Java and specifically in using stacks. It is important to understand the fundamentals of stacks and how they work before attempting to convert your calculator to an RPN calculator. You can also try doing some research and reading tutorials on stack implementation in Java. Additionally, you may want to consider using a debugging tool to help you understand where to use the pop method in your code. Good luck with your project!
 

1. What is a Java stack calculator?

A Java stack calculator is a program that allows users to perform mathematical operations using the Reverse Polish Notation (RPN) method. It uses a stack data structure to store and manipulate numbers and operators, allowing for efficient calculation and easy error handling.

2. How does RPN conversion work in a Java stack calculator?

RPN conversion in a Java stack calculator involves converting a mathematical expression from the standard infix notation to the postfix notation used in RPN. This is done by following a set of rules which prioritize the order of operations and use a stack to rearrange the expression. The resulting RPN expression can then be evaluated using the stack calculator.

3. Is a Java stack calculator suitable for beginners?

Yes, a Java stack calculator is a great tool for beginners learning about RPN and stack data structures. It offers a simplified approach to performing mathematical calculations and can help users better understand the concepts behind RPN and stacks.

4. What are the advantages of using a Java stack calculator?

One advantage of using a Java stack calculator is the ability to easily handle complex mathematical expressions and equations. It also provides a more efficient and accurate way of calculating expressions compared to traditional methods. Additionally, its use of a stack data structure allows for easy error handling and debugging.

5. Are there any limitations to using a Java stack calculator?

While a Java stack calculator offers many benefits, it also has some limitations. One limitation is that it may not be suitable for all types of mathematical calculations, such as those involving trigonometric functions or complex numbers. Additionally, it may take some time for users to become familiar with the RPN method and its rules.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
1
Views
922
  • Programming and Computer Science
Replies
14
Views
3K
  • Programming and Computer Science
Replies
9
Views
4K
  • Programming and Computer Science
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
5K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
  • Programming and Computer Science
Replies
1
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
Back
Top