Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

mport java.awt.*; import java.awt.event.*; import java.beans.Expression; import java.util.*; import javax.swing.*; import java.util.Stack; import java.util.StringTokenizer; import java.awt.*; import java.awt.event.*; import java.time.temporal.ValueRange; import javax.swing.*; @SuppressWarnings(serial) public class

mport java.awt.*;

import java.awt.event.*;

import java.beans.Expression;

import java.util.*;

import javax.swing.*;

import java.util.Stack;

import java.util.StringTokenizer;

import java.awt.*;

import java.awt.event.*;

import java.time.temporal.ValueRange;

import javax.swing.*;

@SuppressWarnings("serial")

public class GUIInfixExperim9 extends JFrame implements ActionListener

{

private JFrame frame = new JFrame(); // generic JFrame for error message

private JLabel infixLabel = new JLabel("Enter an infix expression: "); //label for the text field

private JTextField infixExpression = new JTextField(10); // user input for the infix expression

private JButton evaluate = new JButton ("Evaluate"); //the evaluate button

private JLabel resultLabel = new JLabel("Result: "); // the result textfield label

private JTextField infixResult = new JTextField(5); //the result textfield

public GUIInfixExperim9()

{

setLayout(new FlowLayout());//sets the frame to a flowlayout

this.setTitle("Infix Expression Evaluator"); //sets the frame title

this.setSize(200,175); //sets the size of the frame

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //ends the program on when the window is closed

infixResult.setEditable(false); //makes the results uneditable

add(infixLabel);//adds the infixLabel to the frame

add(infixExpression); //adds the infixExpression textfield to the frame

add(evaluate); //adds the evaluate button to the frame

add(resultLabel); // adds the resultLabel to the frame

add(infixResult); // adds the infixResult textfield to the frame

evaluate.addActionListener(this); //adds an ActionListener to the evaluate button

this.setLocationRelativeTo(null);

}

public void actionPerformed(ActionEvent event)

{

//gets the users input from the textfield

Object buttonPress = event.getSource(); //creates an Object to listen for the required event

if(buttonPress ==evaluate) // the following will occur is the evaluate button id pressed

try //will try to evaluate the problem based on the user's input

{

infixResult.setText(String.valueOf(infixExpression));

}

catch (ArithmeticException e)// if there is a divide by zero in the expression an error message will appear

{

JOptionPane.showMessageDialog(frame, "DIVIDE BY ZERO ERROR",

"DIVIDE BY ZERO ERROR", JOptionPane.ERROR_MESSAGE);

}

infixExpression.addMouseListener(new MouseAdapter()// resets the text field when the user clicks the textfield

{

@Override

public void mouseClicked(MouseEvent e)

{

infixExpression.setText("");

}

});

//public void display()

{

setVisible(true);

}

//---------------

//

//

class MyInfixProj {

@SuppressWarnings({ "rawtypes", "unchecked" })

public String Infix( String express, Stack operatorStack){

String Str;

String tokens = null;

//Remove space in the expression

express= express.replaceAll("\\s+","")+ "=";

String operator= "()*/ +-=";

//StringTokenizer tokens = new StringTokenizer(express,operator, true);

while(tokens.hasMoreToken()){

String[] tkn = tokens.nextToken();

if(operator.indexOf(tokens)< 0);

Stack valueStack = null;

valueStack.push(tokens);

//else

operator.push(tokens);

}

return result;

}

import java.util.StringTokenizer;

public class InfixFullParantEx {

public static String evaluateInfix(String exps){

/**remove if any spaces from the expression**/

exps = exps.replaceAll("\\s+", "");

/**we assume that the expression is in valid format**/

MyGenericsStack stack = new MyGenericsStack(exps.length());

/**break the expression into tokens**/

StringTokenizer tokens = new StringTokenizer(exps, "{}()*/+-", true);

while(tokens.hasMoreTokens()){

String tkn = tokens.nextToken();

/**read each token and take action**/

if(tkn.equals("(")

|| tkn.equals("{")

|| tkn.matches("[0-9]+")

|| tkn.equals("*")

|| tkn.equals("/")

|| tkn.equals("+")

|| tkn.equals("-")){

/**push token to the stack**/

stack.push(tkn);

} else if(tkn.equals("}") || tkn.equals(")")){

try {

int op2 = Integer.parseInt(stack.pop());

String oprnd = stack.pop();

int op1 = Integer.parseInt(stack.pop());

/**Below pop removes either } or ) from stack**/

if(!stack.isStackEmpty()){

stack.pop();

}

int result = 0;

if(oprnd.equals("*")){

result = op1*op2;

} else if(oprnd.equals("/")){

result = op1/op2;

} else if(oprnd.equals("+")){

result = op1+op2;

} else if(oprnd.equals("-")){

result = op1-op2;

}

/**push the result to the stack**/

stack.push(result+"");

} catch (Exception e) {

e.printStackTrace();

break;

}

}

}

String finalResult = "";

try {

finalResult = stack.pop();

} catch (Exception e) {

e.printStackTrace();

}

return finalResult;

}

public static void main(String a[]){

String expr = "((2*5)+(6/2))";

System.out.println("Expression: "+expr);

System.out.println("Final Result: "+evaluateInfix(expr));

expr = "(((2 * 5) - (1 * 2)) / (11 - 9))";

System.out.println("Expression: "+expr);

System.out.println("Final Result: "+evaluateInfix(expr));

}

}

/**

* Stack implementation

*/

class MyGenericsStack {

private int stackSize;

private T[] stackArr;

private int top;

/**

* constructor to create stack with size

* @param size

*/

@SuppressWarnings("unchecked")

public MyGenericsStack(int size) {

this.stackSize = size;

this.stackArr = (T[]) new Object[stackSize];

this.top = -1;

}

/**

* This method adds new entry to the top

* of the stack

* @param entry

* @throws Exception

*/

public void push(T entry){

if(this.isStackFull()){

System.out.println(("Stack is full. Increasing the capacity."));

this.increaseStackCapacity();

}

System.out.println("Adding: "+entry);

this.stackArr[++top] = entry;

}

/**

* This method removes an entry from the

* top of the stack.

* @return

* @throws Exception

*/

public T pop() throws Exception {

if(this.isStackEmpty()){

throw new Exception("Stack is empty. Can not remove element.");

}

T entry = this.stackArr[top--];

System.out.println("Removed entry: "+entry);

return entry;

}

/**

* This method returns top of the stack

* without removing it.

* @return

*/

public T peek() {

return stackArr[top];

}

private void increaseStackCapacity(){

@SuppressWarnings("unchecked")

T[] newStack = (T[]) new Object[this.stackSize*2];

for(int i=0;i

newStack[i] = this.stackArr[i];

}

this.stackArr = newStack;

this.stackSize = this.stackSize*2;

}

/**

* This method returns true if the stack is

* empty

* @return

*/

public boolean isStackEmpty() {

return (top == -1);

}

/**

* This method returns true if the stack is full

* @return

*/

public boolean isStackFull() {

return (top == stackSize - 1);

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Programming questions

Question

What part of a neuron responsible for receiving information?

Answered: 1 week ago

Question

18. Why does a subsidy create a deadweight loss?

Answered: 1 week ago