An expresion is in prefix form when operators are written before their operation
ID: 3622360 • Letter: A
Question
An expresion is in prefix form when operators are written before their operations. Here are some examples of prefix expressions and the values they evaluate to:Expression Value
12 12
+ 2 51 53
* 5 7 35
* + 16 4 + 3 1 80
An expression (such as 12) that begins with an integer is a prefix expression thet evaluates to itselt. Otherwise, an expression is a prefix expression if it begins with an operator and is followed by two prefix expressions. In this latter case, the value of the expression is resursively computed from the values of its constituent prefix sub-expressions.
Write a program that allows the user to enter prefix expression in a text field. The program reads the expression, evaluates it, and displays the value in a suitable GUI component. Assume that the user enters expressions that use only positive integers and the two operators + and *. Your program should use a stack to store values of sub-expression as they are computed.
Explanation / Answer
Dear... import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.*; import javax.swing.*; public class PrefixCalc extends JFrame implements ActionListener { JTextField calcIn = new JTextField(20); JTextField calcOut = new JTextField(20); public static void main(String[] args) { PrefixCalc frame = new PrefixCalc(); frame.doSomething(); } void doSomething() { Container c = getContentPane(); c.setLayout(new FlowLayout()); c.add(new JLabel("Enter formula:")); c.add(calcIn); JButton b1 = new JButton("Calculate"); b1.setActionCommand("calculate"); b1.addActionListener(this); c.add(b1); c.add(new JLabel("Result:")); c.add(calcOut); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { try { Stack operations = new Stack(); String[] ops = calcIn.getText().split("\s+"); for (String op : ops) { operations.add(op); } if (operations.size() < 3) { JOptionPane.showMessageDialog(rootPane, "Not enough parameters!"); return; } Integer total = 0; Integer i1 = Integer.parseInt(operations.pop()); Integer i2 = Integer.parseInt(operations.pop()); String newOp = operations.pop(); if ("+".equals(newOp)) { total = i1 + i2; } else { total = i1 * i2; } while (operations.size() > 1) { i2 = Integer.parseInt(operations.pop()); newOp = operations.pop(); if ("+".equals(newOp)) { total = total + i2; } else { total = total * i2; } } calcOut.setText(total.toString()); } catch (Exception ioe) { JOptionPane.showMessageDialog(rootPane, ioe); } } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.