当前位置: 首页 > 面试题库 >

带有String []数组的Java postfix计算器push / pop方法[重复]

鲜于星波
2023-03-14
问题内容

我创建了一个引用后缀计算器的新类。这使用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();
}

}

当我运行代码时,它返回以下错误消息:

    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)

它指向:

        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);
        }

我尝试通过String Builder方法将字符串数组转换为字符串。

后缀计算的逻辑如下:

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

完整的程序粘贴在下面,我正在创建一个GUI后缀计算器。我必须在String中使用split()方法返回正确的getText()输出。

我已经在下面粘贴了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;
}

我在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);
                }

            }
        }
    }
}

}


问题答案:

您将字符串存储"22+"在其中String[] str = {"22+"};,然后尝试将其用作数字a =Integer.parseInt(stack.peek());

因此,如果要使用该表示法,则必须解析stack.peek()结果。

如果您知道那peek()将会返回,22+那么您可以执行以下操作:

stack.peek().split("\\+")[0]

顺便说一句,java.lang.NumberFormatException: For input string: "[22+]"确切的是,您正在尝试使用无效22+的整数字符串转换数字。返回此错误的行是:Integer.parseInt(stack.peek());

调试器可以帮助您发现此问题,并且可以通过划分以下内容轻松地看到它:

a = Integer.parseInt(stack.peek());

进入:

String elem = stack.peek();
a = Integer.parseInt(elem);


 类似资料:
  • 本文向大家介绍JS数组方法push()、pop()用法实例分析,包括了JS数组方法push()、pop()用法实例分析的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了JS数组方法push()、pop()用法。分享给大家供大家参考,具体如下: push()方法 1. 定义:向数组的末尾添加一个或更多元素,并返回新的长度。 2. 语法: arr.push(element1, ..., elem

  • 问题内容: 我试图从我在主java文件中创建的数组中添加,删除和引用项目,但是我在弄清楚正确的语法时遇到了麻烦。在动作脚本中,它们具有push()和pop()来添加和删除数组中的项目,android中是否有等效项? 问题答案: 在Java中,数组的大小是固定的(初始化后),这意味着您无法在数组中添加或删除项目。 上面的代码段表示整数数组的长度为10。如果不将引用重新分配给新数组,则不能添加第11个

  • 问题内容: 我为使用堆栈的程序创建的2个类有问题。我得到的第一个问题是,当我尝试运行程序时,出现运行时错误。 这很难问,因为它做了很多事情。它要求用户输入以将数字添加到堆栈中,并检查堆栈是满还是空。我也可能需要帮助来复制阵列。 线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:在Lab15.main(Lab15.java:38)处在IntegerS

  • 本文向大家介绍JavaScript数组函数unshift、shift、pop、push使用实例,包括了JavaScript数组函数unshift、shift、pop、push使用实例的使用技巧和注意事项,需要的朋友参考一下 如何声明数组 s中数组的声明可以有几种方式声明 在new数组的时候可以传入一个参数,表示数组的初始化长度 但如果你想创建一个只有一个元素3的数组,那么使用 new 方法是不能实

  • 本文向大家介绍mongodb 修改器($inc/$set/$unset/$push/$pop/upsert),包括了mongodb 修改器($inc/$set/$unset/$push/$pop/upsert)的使用技巧和注意事项,需要的朋友参考一下 对于文档的更新除替换外,针对某个或多个文档只需要部分更新可使用原子的更新修改器,能够高效的进行文档更新。更新修改器是中特殊的键, 用来指定复杂的操作

  • 本文向大家介绍Javascript数组中push方法用法分析,包括了Javascript数组中push方法用法分析的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Javascript数组中push方法用法。分享给大家供大家参考,具体如下: 看下面代码: Q:o现在内部的值是什么样子? 我的第一反应是排斥,为什么要研究不合理情况下【解释引擎】的行为?但是这种推论有时候又很吸引人,于是我回来的