带有 String[] 数组的 Java 后缀计算器 push/pop 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24725374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java postfix calculator push/pop method with a String[] array
提问by Axion004
I have created a new class that references a postfix calculator. This uses the push()
and pop()
methods. Here is the code (Updated from comments below using a String Builder()):
我创建了一个引用后缀计算器的新类。这使用push()
和pop()
方法。这是代码(使用 String Builder() 从下面的注释更新):
import java.util.Stack;
import java.util.*;
import java.io.*;
public class StackCalculation
{
public static void main (String[] args) throws Exception
{
String[] str = {"22+"};
String string = convertStringArrayToString(str);
System.out.println(string);
Stack<String> stack = new Stack<String>();
stack.add(string);
double a = 0;
double b = 0;
double sum = 0;
while (!stack.isEmpty())
{
if(stack.peek().equals("+"))
{
a = Double.parseDouble(stack.peek());
stack.pop();
b = Double.parseDouble(stack.peek());
stack.pop();
sum = a + b;
//Write something to push back the sum of the last 2 numbers a + b
stack.push("" + sum);
}
else if(stack.peek().equals("*"))
{
a = Double.parseDouble(stack.peek());
stack.pop();
b = Double.parseDouble(stack.peek());
stack.pop();
sum = a * b;
//Write something to push back the product of the last 2 numbers a * b
stack.push("" + sum);
}
else if(stack.peek().equals("-"))
{
a = Double.parseDouble(stack.peek());
stack.pop();
b = Double.parseDouble(stack.peek());
stack.pop();
sum = a - b;
//Write something to push back the difference of the last 2 numbers a - b
stack.push("" + sum);
}
else if(stack.peek().equals("/"))
{
a = Double.parseDouble(stack.peek());
stack.pop();
b = Double.parseDouble(stack.peek());
stack.pop();
sum = a / b;
//Write something to push back the quotient of the last 2 numbers a/b
stack.push("" + sum);
}
else
{
//Convert the last item in the stack to a double and push
//this into the stack
String elem = stack.peek();
a = Double.parseDouble(elem);
stack.push("" + a);
}
}
System.out.println(stack);
//System.out.println(string);
}
private static String convertStringArrayToString(String[] strArr) {
StringBuilder sb = new StringBuilder();
for(String str : strArr) sb.append(str);
return sb.toString();
}
}
}
When I run the code, it returns this error message:
当我运行代码时,它返回此错误消息:
Exception in thread "main" java.lang.NumberFormatException: For input string: "22+"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at StackCalculation.main(StackCalculation.java:69)
It points to:
它指出:
else
{
//Convert the last item in the stack to a double and push
//this into the stack
String elem = stack.peek();
a = Double.parseDouble(elem);
stack.push("" + a);
}
I tried passing through a String Builder method to convert the string array into a string.
我尝试通过 String Builder 方法将字符串数组转换为字符串。
The logic behind postfix calculation is as follows:
后缀计算背后的逻辑如下:
read in a symbol (number or operator)
As long as you're not at the end of the entire string yet
if the symbol is +
pop the last 2 values from the stack
push back their sum
else if the symbol is *
pop the last 2 values from the stack and
push back their product
else if the symbol is –
pop the last 2 values from the stack and
push back the difference (second value – first value)
else if the symbol is /
pop the last 2 values from the stack
push back the quotient (second value / first value)
else if symbol is =
print the top of the stack
pop the stack
else if the symbol is a number
convert to a double and push it on the stack; read the next symbol,
repeat above steps and do until you're at the end of the string
The full program is pasted below, I am creating a GUI postfix calculator. I had to use the split() method in String to return the correct getText() output.
完整的程序粘贴在下面,我正在创建一个 GUI 后缀计算器。我必须在 String 中使用 split() 方法来返回正确的 getText() 输出。
I have pasted the original code for the GUI operation below. I am making a new class to test the results of the following method-
我在下面粘贴了 GUI 操作的原始代码。我正在创建一个新类来测试以下方法的结果-
// Use the String's split method to get rid of spaces
public String[] getStringOutput()
{
String str = calculatorLabel.getText();
String[] string = str.split(" ");
return string;
}
I am referencing this method inside the calcButtonListener() class which needs to do the postfix calculation when the "Calculate" button is clicked.I don't know of any any way to write the private class calcButtonListener() at the very end.
我在 calcButtonListener() 类中引用了这个方法,当点击“计算”按钮时,它需要进行后缀计算。我不知道有什么方法可以在最后编写私有类 calcButtonListener()。
import javax.swing.*;
import javax.swing.border.Border;
import java.util.Arrays;
import java.util.Stack;
import java.awt.*;
import java.awt.event.*;
public class PostfixCalculator extends JFrame
{
private JPanel calculatedResultPanel;
private JPanel northPanel;
private JPanel centerPanel;
private JPanel southPanel;
private JPanel num1Panel;
private JPanel num2Panel;
private JPanel num3Panel;
private JPanel num4Panel;
private JPanel num5Panel;
private JPanel num6Panel;
private JPanel num7Panel;
private JPanel num8Panel;
private JPanel num9Panel;
private JPanel addPanel;
private JPanel subtractPanel;
private JPanel multiplyPanel;
private JPanel dividePanel;
private JPanel zeroPanel;
private JPanel spacePanel;
private JPanel calculatePanel;
private JPanel clearPanel;
private JButton zero;
private JButton one;
private JButton two;
private JButton three;
private JButton four;
private JButton five;
private JButton six;
private JButton seven;
private JButton eight;
private JButton nine;
private JButton add;
private JButton subtract;
private JButton multiply;
private JButton divide;
private JButton space;
private JButton calculate;
private JButton clear;
private JLabel calculatorLabel;
private final int WINDOW_WIDTH = 350;
private final int WINDOW_HEIGHT = 250;
// Main
public static void main(String[] args)
{
new PostfixCalculator();
}
// Constructor
public PostfixCalculator()
{
setTitle("Posfix Calculator");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel and add it to the frame
buildPanel();
//Get the string output from the buttons pressed
getStringOutput();
// Display the window
setVisible(true);
}
// The buildPanel method is created to add a label, text field,
// and a button to the panel
public void buildPanel()
{
// Use the insert containers method
insertContainers();
// Adjust the north panel to display the label bar
Border border = BorderFactory.createLineBorder(Color.BLACK, 1);
calculatorLabel.setBorder(border);
calculatorLabel.setPreferredSize(new Dimension(150, 25));
calculatedResultPanel.add(calculatorLabel);
northPanel.add(calculatedResultPanel);
add(northPanel, BorderLayout.NORTH);
// Adjust the east panel to display the majority
// of the buttons
centerPanel.setLayout(new GridLayout(4,4));
num1Panel.add(one);
num2Panel.add(two);
num3Panel.add(three);
addPanel.add(add);
num4Panel.add(four);
num5Panel.add(five);
num6Panel.add(six);
subtractPanel.add(subtract);
num7Panel.add(seven);
num8Panel.add(eight);
num9Panel.add(nine);
multiplyPanel.add(multiply);
zeroPanel.add(zero);
clearPanel.add(clear);
dividePanel.add(divide);
centerPanel.add(num1Panel);
centerPanel.add(num2Panel);
centerPanel.add(num3Panel);
centerPanel.add(addPanel);
centerPanel.add(num4Panel);
centerPanel.add(num5Panel);
centerPanel.add(num6Panel);
centerPanel.add(subtractPanel);
centerPanel.add(num7Panel);
centerPanel.add(num8Panel);
centerPanel.add(num9Panel);
centerPanel.add(multiplyPanel);
centerPanel.add(Box.createRigidArea(new Dimension(0,5)));
centerPanel.add(zeroPanel);
centerPanel.add(clearPanel);
centerPanel.add(dividePanel);
add(centerPanel, BorderLayout.CENTER);
// Put the remaining buttons and labels inside the South panel
southPanel.setLayout(new GridLayout(1,3));
calculatePanel.add(calculate);
spacePanel.add(space);
southPanel.add(Box.createRigidArea(new Dimension(0,5)));
southPanel.add(calculatePanel);
southPanel.add(spacePanel);
add(southPanel, BorderLayout.SOUTH);
// Add the action listeners to the panel
zero.addActionListener(new buttonListener());
one.addActionListener(new buttonListener());
two.addActionListener(new buttonListener());
three.addActionListener(new buttonListener());
four.addActionListener(new buttonListener());
five.addActionListener(new buttonListener());
six.addActionListener(new buttonListener());
seven.addActionListener(new buttonListener());
eight.addActionListener(new buttonListener());
nine.addActionListener(new buttonListener());
add.addActionListener(new buttonListener());
subtract.addActionListener(new buttonListener());
multiply.addActionListener(new buttonListener());
divide.addActionListener(new buttonListener());
space.addActionListener(new buttonListener());
clear.addActionListener(new buttonListener());
//Add the action listener for the calculate button
calculate.addActionListener(new buttonListener());
}
// Insert the panels, buttons and labels into the frame
public void insertContainers()
{
// Insert a label for the calculator output
calculatorLabel = new JLabel("");
// Create the panels
calculatedResultPanel = new JPanel();
northPanel = new JPanel();
centerPanel = new JPanel();
southPanel = new JPanel();
// Create the specialized panels
num1Panel = new JPanel();
num2Panel = new JPanel();
num3Panel = new JPanel();
num4Panel = new JPanel();
num5Panel = new JPanel();
num6Panel = new JPanel();
num7Panel = new JPanel();
num8Panel = new JPanel();
num9Panel = new JPanel();
addPanel = new JPanel();
subtractPanel = new JPanel();
multiplyPanel = new JPanel();
zeroPanel = new JPanel();
clearPanel = new JPanel();
dividePanel = new JPanel();
calculatePanel = new JPanel();
spacePanel = new JPanel();
// Create the buttons to be displayed
one = new JButton("1");
two = new JButton("2");
three = new JButton("3");
four = new JButton("4");
five = new JButton("5");
six = new JButton("6");
seven = new JButton("7");
eight = new JButton("8");
nine = new JButton("9");
add = new JButton("+");
subtract = new JButton("-");
multiply = new JButton("*");
zero = new JButton("0");
clear = new JButton("C");
divide = new JButton("/");
calculate = new JButton("Calculate");
space = new JButton("_");
}
// Use the String's split method to get rid of spaces
public String[] getStringOutput()
{
String str = calculatorLabel.getText();
String[] string = str.split(" ");
return string;
}
// Needed to convert the getStringOutput() method above from a String[] to a String.
private static String convertStringArrayToString(String[] strArr) {
StringBuilder sb = new StringBuilder();
for(String str : strArr) sb.append(str);
return sb.toString();
}
// Add the button pressed to the JLabel field
private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// Determine which button was clicked and add this to the JLabel
if( e.getSource() == zero)
calculatorLabel.setText(calculatorLabel.getText() + "0");
if( e.getSource() == one)
calculatorLabel.setText(calculatorLabel.getText() + "1");
if( e.getSource() == two)
calculatorLabel.setText(calculatorLabel.getText() + "2");
if( e.getSource() == three)
calculatorLabel.setText(calculatorLabel.getText() + "3");
if( e.getSource() == four)
calculatorLabel.setText(calculatorLabel.getText() + "4");
if( e.getSource() == five)
calculatorLabel.setText(calculatorLabel.getText() + "5");
if( e.getSource() == six)
calculatorLabel.setText(calculatorLabel.getText() + "6");
if( e.getSource() == seven)
calculatorLabel.setText(calculatorLabel.getText() + "7");
if( e.getSource() == eight)
calculatorLabel.setText(calculatorLabel.getText() + "8");
if( e.getSource() == nine)
calculatorLabel.setText(calculatorLabel.getText() + "9");
if( e.getSource() == add)
calculatorLabel.setText(calculatorLabel.getText() + "+");
if( e.getSource() == subtract)
calculatorLabel.setText(calculatorLabel.getText() + "-");
if( e.getSource() == multiply)
calculatorLabel.setText(calculatorLabel.getText() + "*");
if( e.getSource() == divide)
calculatorLabel.setText(calculatorLabel.getText() + "/");
if( e.getSource() == space)
calculatorLabel.setText(calculatorLabel.getText() + " ");
if( e.getSource() == clear)
calculatorLabel.setText("");
}
// Create the calculator button action listener.
// Add the button pressed to the JLabel field
private class calcButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String[] str = getStringOutput();
String string = convertStringArrayToString(str);
Stack<String> stack = new Stack<String>();
stack.add(string);
double a = 0;
double b = 0;
double sum = 0;
while (!stack.isEmpty())
{
if(stack.peek().equals("+"))
{
a = Double.parseDouble(stack.peek());
stack.pop();
b = Double.parseDouble(stack.peek());
stack.pop();
sum = a + b;
//Write something to push back the sum of the last 2 numbers a + b
stack.push("" + sum);
}
else if(stack.peek().equals("*"))
{
a = Double.parseDouble(stack.peek());
stack.pop();
b = Double.parseDouble(stack.peek());
stack.pop();
sum = a * b;
//Write something to push back the product of the last 2 numbers a * b
stack.push("" + sum);
}
else if(stack.peek().equals("-"))
{
a = Double.parseDouble(stack.peek());
stack.pop();
b = Double.parseDouble(stack.peek());
stack.pop();
sum = a - b;
//Write something to push back the difference of the last 2 numbers a - b
stack.push("" + sum);
}
else if(stack.peek().equals("/"))
{
a = Double.parseDouble(stack.peek());
stack.pop();
b = Double.parseDouble(stack.peek());
stack.pop();
sum = a / b;
//Write something to push back the quotient of the last 2 numbers a/b
stack.push("" + sum);
}
else
{
//Convert the last item in the stack to a double and push
//this into the stack
String elem = stack.peek();
a = Double.parseDouble(elem);
stack.push("" + a);
}
}
}
}
}
}
}
采纳答案by Federico Piazza
You are storing the string "22+"
in String[] str = {"22+"};
and then you are trying to use it as number in a = Integer.parseInt(stack.peek());
您将字符串存储"22+"
在String[] str = {"22+"};
,然后您尝试将其用作数字a = Integer.parseInt(stack.peek());
So, if you want to use that notation, you will have to parse your stack.peek()
result.
因此,如果您想使用该符号,则必须解析stack.peek()
结果。
If you know that peek()
will return 22+
so you can do:
如果您知道这peek()
会返回,22+
那么您可以执行以下操作:
stack.peek().split("\+")[0]
Btw, the java.lang.NumberFormatException: For input string: "[22+]"
is exactly that, you are trying to convert a number using the invalid string 22+
for an integer. The line which return this error is: Integer.parseInt(stack.peek());
顺便说一句,java.lang.NumberFormatException: For input string: "[22+]"
正是这样,您正在尝试使用22+
整数的无效字符串转换数字。返回此错误的行是:Integer.parseInt(stack.peek());
A debugger can help you to find this issue and you can see it easily by dividing:
调试器可以帮助您找到此问题,您可以通过划分以下内容轻松查看:
a = Integer.parseInt(stack.peek());
Into:
进入:
String elem = stack.peek();
a = Integer.parseInt(elem);