SlideShare a Scribd company logo
1 of 14
Download to read offline
Main class :-
-------------------------
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final InfixExperssionEvaluator ie = new InfixExperssionEvaluator();
JFrame frame = new JFrame("FrameDemo");
frame.setSize(600,200);
frame.setLayout(new FlowLayout());
JPanel main = new JPanel(new GridLayout(3, 1));
JPanel panel1 = new JPanel(new GridLayout(1, 2));
panel1.setSize(500, 250);
panel1.add(new JLabel("Enter Infix Expression"));
final JTextField field1 = new JTextField();
field1.setSize(150,100);
panel1.add(field1);
main.add(panel1);
JPanel panel2 = new JPanel(new GridLayout(1, 1));
panel1.setSize(300, 150);
JButton button = new JButton();
button.setSize(200, 100);
button.setText("Submit");
panel2.add(button);
main.add(panel2);
JPanel panel3 = new JPanel(new GridLayout(1, 2));
panel3.add(new JLabel("Value : "));
final JLabel lbl = new JLabel();
panel3.add(lbl);
main.add(panel3);
frame.getContentPane().add(main);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if ("Submit".equals(e.getActionCommand())) {
String expr = field1.getText();
lbl.setText(Double.toString(ie.infixToValue(expr)));
}
}
});
button.setActionCommand("Submit");
String expr = "((2*5)+(6/2))";
System.out.println("value is ::"+ ie.infixToValue(expr));
}
}
Class for Evaluate methods :-
-----------------------------------------
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.StringTokenizer;
public class InfixExperssionEvaluator {
Stack expressionStack = new Stack();
Stack valueStack = new Stack(); //to hold only non-decimal values
public static final String OPERATORS="+-/*()"; //ignore the "(" as an operator
//Map For Operator precedence Key(+,-,*,/) , value 0/1/2/3..
Map operator_levels = new HashMap();
public InfixExperssionEvaluator(){
operator_levels.put(")", 0);
operator_levels.put("*", 1);
operator_levels.put("/", 1);
operator_levels.put("+", 2);
operator_levels.put("-", 2);
operator_levels.put("(", 3);
}
double infixToValue(String inputExpression) {
String eachNumber=""; //to hold multiple digit values. lame idea, i know, but can't
think of anything else at 2 AM
int totalCharInInput = inputExpression.length();
inputExpression.replaceAll("s+","");
//Devide String to Tokens
StringTokenizer tokens = new StringTokenizer(inputExpression, "{}()*/+-", true);
//Loop through each Token
while(tokens.hasMoreTokens()){
String eachChar = tokens.nextToken();
if (isValidOperator(eachChar)){
//We could stack up a lot of left parenthesis in the beginning without reaching a
number. Weed it out
if (!isLeftParen(eachChar) && isNumeric(eachNumber)){
valueStack.push(Long.parseLong(eachNumber)); //push the till now accumulated
number to the value stack
eachNumber="";
}
if (expressionStack.isEmpty() || isLeftParen(eachChar)){ //first item or left
parenthesis
expressionStack.push(eachChar);
}
else if (isRightParen(eachChar)){
evaluateAndPushValueToStackUntilLeftParenthesis(valueStack,
expressionStack);
}
//if the current operator has higher precedence than the first item in the stack, then it
is fine.
//Just insert the incoming
else if (getHigherPrecedenceOperator(eachChar,
expressionStack.peek()).equals(eachChar)){
expressionStack.push(eachChar);
}
//if the current operator is lesser, then the previous higher precedence expression
have to be
//evaluated. Else, we would be making wrong calculations while popping off for
final evaluation
else if(valueStack.size() > 2){
//the current operator has higher precedence. Evaluate expression
evaluateAndPushValueToValueStack(valueStack, expressionStack);
//after evaluation of the higher pair, don't forget to insert the current character
into the expression stack
expressionStack.push(eachChar);
}
}
else if (isNumeric(eachChar)){
eachNumber+=eachChar;
if (totalCharInInput==0){
valueStack.push(Long.parseLong(eachNumber)); //the last element
}
}
System.out.println ("Value Stack : "+valueStack);
System.out.println ("Expression Stack : "+expressionStack);
}
System.out.println("Final Expression stack " +expressionStack);
System.out.println("Final Value stack : "+valueStack);
while (!expressionStack.empty()){
evaluateAndPushValueToValueStack(valueStack,expressionStack);
}
System.out.println ("Final value : "+valueStack);
return valueStack.pop();
}
boolean isRightParen(String operator) {
return (operator.equals(")")?true:false);
}
boolean isLeftParen(String operator) {
return (operator.equals("(")?true:false);
}
//Evaluate and push reslt to value stack
private void evaluateAndPushValueToValueStack(Stack valueStack, Stack
expressionStack) {
Long firstOperand=valueStack.pop();
Long secondOperand=valueStack.pop();
System.out.println ("Value stack : "+firstOperand+ ":"+ secondOperand );
Long evaluatedValue = this.evaluate(secondOperand, firstOperand,
expressionStack.pop()); //intermediate result
valueStack.push(evaluatedValue);
}
//Evaluate current statck
private void evaluateAndPushValueToStackUntilLeftParenthesis(Stack valueStack, Stack
expressionStack) {
while (!expressionStack.empty()){
if (isLeftParen(expressionStack.peek())){ //if the left parenthesis has been reached,
then pop it up and exit
expressionStack.pop();
break;
}
evaluateAndPushValueToValueStack(valueStack,expressionStack);
}
}
//Caclulate result for 2 oprands and one operator
Long evaluate(Long firstOperand, Long secondOperand, String operator) throws
ArithmeticException{
Long returnValue = (long) 0;
switch (operator) {
case "+" :
returnValue=firstOperand+secondOperand;
break;
case "-" :
returnValue=firstOperand-secondOperand;
break;
case "*":
returnValue=firstOperand*secondOperand;
break;
case "/":
if (secondOperand==0){ //cheating death by zero
returnValue=(long) 0;
throw new ArithmeticException("Divide by zero");
}
else{
returnValue = firstOperand/secondOperand;
}
break;
}
return returnValue;
}
//Check whether String is operator or not
boolean isValidOperator(String input) {
return (OPERATORS.contains(input)?true:false);
}
//Check Precedence
String getHigherPrecedenceOperator(String firstOperator, String secondOperator){
return (operator_levels.get(firstOperator) <
operator_levels.get(secondOperator)?firstOperator:secondOperator);
}
//Check whether String is number or not
public static boolean isNumeric(String str)
{
return str.matches("-?d+(.d+)?"); //match a number with optional '-' and
decimal.
}
}
Solution
Main class :-
-------------------------
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final InfixExperssionEvaluator ie = new InfixExperssionEvaluator();
JFrame frame = new JFrame("FrameDemo");
frame.setSize(600,200);
frame.setLayout(new FlowLayout());
JPanel main = new JPanel(new GridLayout(3, 1));
JPanel panel1 = new JPanel(new GridLayout(1, 2));
panel1.setSize(500, 250);
panel1.add(new JLabel("Enter Infix Expression"));
final JTextField field1 = new JTextField();
field1.setSize(150,100);
panel1.add(field1);
main.add(panel1);
JPanel panel2 = new JPanel(new GridLayout(1, 1));
panel1.setSize(300, 150);
JButton button = new JButton();
button.setSize(200, 100);
button.setText("Submit");
panel2.add(button);
main.add(panel2);
JPanel panel3 = new JPanel(new GridLayout(1, 2));
panel3.add(new JLabel("Value : "));
final JLabel lbl = new JLabel();
panel3.add(lbl);
main.add(panel3);
frame.getContentPane().add(main);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if ("Submit".equals(e.getActionCommand())) {
String expr = field1.getText();
lbl.setText(Double.toString(ie.infixToValue(expr)));
}
}
});
button.setActionCommand("Submit");
String expr = "((2*5)+(6/2))";
System.out.println("value is ::"+ ie.infixToValue(expr));
}
}
Class for Evaluate methods :-
-----------------------------------------
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.StringTokenizer;
public class InfixExperssionEvaluator {
Stack expressionStack = new Stack();
Stack valueStack = new Stack(); //to hold only non-decimal values
public static final String OPERATORS="+-/*()"; //ignore the "(" as an operator
//Map For Operator precedence Key(+,-,*,/) , value 0/1/2/3..
Map operator_levels = new HashMap();
public InfixExperssionEvaluator(){
operator_levels.put(")", 0);
operator_levels.put("*", 1);
operator_levels.put("/", 1);
operator_levels.put("+", 2);
operator_levels.put("-", 2);
operator_levels.put("(", 3);
}
double infixToValue(String inputExpression) {
String eachNumber=""; //to hold multiple digit values. lame idea, i know, but can't
think of anything else at 2 AM
int totalCharInInput = inputExpression.length();
inputExpression.replaceAll("s+","");
//Devide String to Tokens
StringTokenizer tokens = new StringTokenizer(inputExpression, "{}()*/+-", true);
//Loop through each Token
while(tokens.hasMoreTokens()){
String eachChar = tokens.nextToken();
if (isValidOperator(eachChar)){
//We could stack up a lot of left parenthesis in the beginning without reaching a
number. Weed it out
if (!isLeftParen(eachChar) && isNumeric(eachNumber)){
valueStack.push(Long.parseLong(eachNumber)); //push the till now accumulated
number to the value stack
eachNumber="";
}
if (expressionStack.isEmpty() || isLeftParen(eachChar)){ //first item or left
parenthesis
expressionStack.push(eachChar);
}
else if (isRightParen(eachChar)){
evaluateAndPushValueToStackUntilLeftParenthesis(valueStack,
expressionStack);
}
//if the current operator has higher precedence than the first item in the stack, then it
is fine.
//Just insert the incoming
else if (getHigherPrecedenceOperator(eachChar,
expressionStack.peek()).equals(eachChar)){
expressionStack.push(eachChar);
}
//if the current operator is lesser, then the previous higher precedence expression
have to be
//evaluated. Else, we would be making wrong calculations while popping off for
final evaluation
else if(valueStack.size() > 2){
//the current operator has higher precedence. Evaluate expression
evaluateAndPushValueToValueStack(valueStack, expressionStack);
//after evaluation of the higher pair, don't forget to insert the current character
into the expression stack
expressionStack.push(eachChar);
}
}
else if (isNumeric(eachChar)){
eachNumber+=eachChar;
if (totalCharInInput==0){
valueStack.push(Long.parseLong(eachNumber)); //the last element
}
}
System.out.println ("Value Stack : "+valueStack);
System.out.println ("Expression Stack : "+expressionStack);
}
System.out.println("Final Expression stack " +expressionStack);
System.out.println("Final Value stack : "+valueStack);
while (!expressionStack.empty()){
evaluateAndPushValueToValueStack(valueStack,expressionStack);
}
System.out.println ("Final value : "+valueStack);
return valueStack.pop();
}
boolean isRightParen(String operator) {
return (operator.equals(")")?true:false);
}
boolean isLeftParen(String operator) {
return (operator.equals("(")?true:false);
}
//Evaluate and push reslt to value stack
private void evaluateAndPushValueToValueStack(Stack valueStack, Stack
expressionStack) {
Long firstOperand=valueStack.pop();
Long secondOperand=valueStack.pop();
System.out.println ("Value stack : "+firstOperand+ ":"+ secondOperand );
Long evaluatedValue = this.evaluate(secondOperand, firstOperand,
expressionStack.pop()); //intermediate result
valueStack.push(evaluatedValue);
}
//Evaluate current statck
private void evaluateAndPushValueToStackUntilLeftParenthesis(Stack valueStack, Stack
expressionStack) {
while (!expressionStack.empty()){
if (isLeftParen(expressionStack.peek())){ //if the left parenthesis has been reached,
then pop it up and exit
expressionStack.pop();
break;
}
evaluateAndPushValueToValueStack(valueStack,expressionStack);
}
}
//Caclulate result for 2 oprands and one operator
Long evaluate(Long firstOperand, Long secondOperand, String operator) throws
ArithmeticException{
Long returnValue = (long) 0;
switch (operator) {
case "+" :
returnValue=firstOperand+secondOperand;
break;
case "-" :
returnValue=firstOperand-secondOperand;
break;
case "*":
returnValue=firstOperand*secondOperand;
break;
case "/":
if (secondOperand==0){ //cheating death by zero
returnValue=(long) 0;
throw new ArithmeticException("Divide by zero");
}
else{
returnValue = firstOperand/secondOperand;
}
break;
}
return returnValue;
}
//Check whether String is operator or not
boolean isValidOperator(String input) {
return (OPERATORS.contains(input)?true:false);
}
//Check Precedence
String getHigherPrecedenceOperator(String firstOperator, String secondOperator){
return (operator_levels.get(firstOperator) <
operator_levels.get(secondOperator)?firstOperator:secondOperator);
}
//Check whether String is number or not
public static boolean isNumeric(String str)
{
return str.matches("-?d+(.d+)?"); //match a number with optional '-' and
decimal.
}
}

More Related Content

Similar to Main class --------------------------import java.awt.FlowLayout.pdf

Objective Min-heap queue with customized comparatorHospital emerg.pdf
Objective Min-heap queue with customized comparatorHospital emerg.pdfObjective Min-heap queue with customized comparatorHospital emerg.pdf
Objective Min-heap queue with customized comparatorHospital emerg.pdfezhilvizhiyan
 
Java!!!!!Create a program that authenticates username and password.pdf
Java!!!!!Create a program that authenticates username and password.pdfJava!!!!!Create a program that authenticates username and password.pdf
Java!!!!!Create a program that authenticates username and password.pdfarvindarora20042013
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleChristopher Curtin
 
PQTimer.java A simple driver program to run timing t.docx
  PQTimer.java     A simple driver program to run timing t.docx  PQTimer.java     A simple driver program to run timing t.docx
PQTimer.java A simple driver program to run timing t.docxjoyjonna282
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxmary772
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxmccormicknadine86
 
Use arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdfUse arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdffootworld1
 
Othello.javapackage othello;import core.Game; import userInter.pdf
Othello.javapackage othello;import core.Game; import userInter.pdfOthello.javapackage othello;import core.Game; import userInter.pdf
Othello.javapackage othello;import core.Game; import userInter.pdfarccreation001
 
import java.awt.BorderLayout; import java.awt.EventQueue; i.pdf
  import java.awt.BorderLayout;     import java.awt.EventQueue;      i.pdf  import java.awt.BorderLayout;     import java.awt.EventQueue;      i.pdf
import java.awt.BorderLayout; import java.awt.EventQueue; i.pdfnikhilpopli11
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfarjuntelecom26
 

Similar to Main class --------------------------import java.awt.FlowLayout.pdf (20)

Objective Min-heap queue with customized comparatorHospital emerg.pdf
Objective Min-heap queue with customized comparatorHospital emerg.pdfObjective Min-heap queue with customized comparatorHospital emerg.pdf
Objective Min-heap queue with customized comparatorHospital emerg.pdf
 
Java!!!!!Create a program that authenticates username and password.pdf
Java!!!!!Create a program that authenticates username and password.pdfJava!!!!!Create a program that authenticates username and password.pdf
Java!!!!!Create a program that authenticates username and password.pdf
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading example
 
PQTimer.java A simple driver program to run timing t.docx
  PQTimer.java     A simple driver program to run timing t.docx  PQTimer.java     A simple driver program to run timing t.docx
PQTimer.java A simple driver program to run timing t.docx
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
TextSearch
TextSearchTextSearch
TextSearch
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
 
3 j unit
3 j unit3 j unit
3 j unit
 
Use arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdfUse arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdf
 
Othello.javapackage othello;import core.Game; import userInter.pdf
Othello.javapackage othello;import core.Game; import userInter.pdfOthello.javapackage othello;import core.Game; import userInter.pdf
Othello.javapackage othello;import core.Game; import userInter.pdf
 
Java awt
Java awtJava awt
Java awt
 
From Swing to JavaFX
From Swing to JavaFXFrom Swing to JavaFX
From Swing to JavaFX
 
import java.awt.BorderLayout; import java.awt.EventQueue; i.pdf
  import java.awt.BorderLayout;     import java.awt.EventQueue;      i.pdf  import java.awt.BorderLayout;     import java.awt.EventQueue;      i.pdf
import java.awt.BorderLayout; import java.awt.EventQueue; i.pdf
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 

More from anushkaent7

A. ASBRThe router is an ASBR type because all configured networks .pdf
A. ASBRThe router is an ASBR type because all configured networks .pdfA. ASBRThe router is an ASBR type because all configured networks .pdf
A. ASBRThe router is an ASBR type because all configured networks .pdfanushkaent7
 
A TetrahedralB polar becaue there is an uneven distribution of e.pdf
A TetrahedralB polar becaue there is an uneven distribution of e.pdfA TetrahedralB polar becaue there is an uneven distribution of e.pdf
A TetrahedralB polar becaue there is an uneven distribution of e.pdfanushkaent7
 
1)Journal entriesT- AccountsCommon StockCommon Stock dividends.pdf
1)Journal entriesT- AccountsCommon StockCommon Stock dividends.pdf1)Journal entriesT- AccountsCommon StockCommon Stock dividends.pdf
1)Journal entriesT- AccountsCommon StockCommon Stock dividends.pdfanushkaent7
 
1) a.Seasonal H1N1 influenza Seasonal contaminate the superior or u.pdf
1) a.Seasonal H1N1 influenza Seasonal contaminate the superior or u.pdf1) a.Seasonal H1N1 influenza Seasonal contaminate the superior or u.pdf
1) a.Seasonal H1N1 influenza Seasonal contaminate the superior or u.pdfanushkaent7
 
1 mole of 12C contains 6.02 x 1023 carbon atomsSolution1 mole .pdf
1 mole of 12C contains 6.02 x 1023 carbon atomsSolution1 mole .pdf1 mole of 12C contains 6.02 x 1023 carbon atomsSolution1 mole .pdf
1 mole of 12C contains 6.02 x 1023 carbon atomsSolution1 mole .pdfanushkaent7
 
(-3,0)Solution(-3,0).pdf
(-3,0)Solution(-3,0).pdf(-3,0)Solution(-3,0).pdf
(-3,0)Solution(-3,0).pdfanushkaent7
 
Two advantages of using financial accounting information in decision.pdf
Two advantages of using financial accounting information in decision.pdfTwo advantages of using financial accounting information in decision.pdf
Two advantages of using financial accounting information in decision.pdfanushkaent7
 
their joint probability is the product of the probability of the eve.pdf
their joint probability is the product of the probability of the eve.pdftheir joint probability is the product of the probability of the eve.pdf
their joint probability is the product of the probability of the eve.pdfanushkaent7
 
The phylogenetic origin of the flu virus that caused the 2009 pandem.pdf
The phylogenetic origin of the flu virus that caused the 2009 pandem.pdfThe phylogenetic origin of the flu virus that caused the 2009 pandem.pdf
The phylogenetic origin of the flu virus that caused the 2009 pandem.pdfanushkaent7
 
The Program to find out the middle of a given linked listclass Lin.pdf
The Program to find out the middle of a given linked listclass Lin.pdfThe Program to find out the middle of a given linked listclass Lin.pdf
The Program to find out the middle of a given linked listclass Lin.pdfanushkaent7
 
Question 1Answer b. The returned value, return address, paramete.pdf
Question 1Answer b. The returned value, return address, paramete.pdfQuestion 1Answer b. The returned value, return address, paramete.pdf
Question 1Answer b. The returned value, return address, paramete.pdfanushkaent7
 
Plasma membrane of human is made of phospholipids; these are fluids .pdf
Plasma membrane of human is made of phospholipids; these are fluids .pdfPlasma membrane of human is made of phospholipids; these are fluids .pdf
Plasma membrane of human is made of phospholipids; these are fluids .pdfanushkaent7
 
Please post the exact proplem in comments.SolutionPlease post .pdf
Please post the exact proplem in comments.SolutionPlease post .pdfPlease post the exact proplem in comments.SolutionPlease post .pdf
Please post the exact proplem in comments.SolutionPlease post .pdfanushkaent7
 
P( both correct) = P( first correct)P( second correct) = 1212 = .pdf
P( both correct) = P( first correct)P( second correct) = 1212 = .pdfP( both correct) = P( first correct)P( second correct) = 1212 = .pdf
P( both correct) = P( first correct)P( second correct) = 1212 = .pdfanushkaent7
 
One of the functions of skin is to regulate the temperature. The ski.pdf
One of the functions of skin is to regulate the temperature. The ski.pdfOne of the functions of skin is to regulate the temperature. The ski.pdf
One of the functions of skin is to regulate the temperature. The ski.pdfanushkaent7
 
None of the options.SolutionNone of the options..pdf
None of the options.SolutionNone of the options..pdfNone of the options.SolutionNone of the options..pdf
None of the options.SolutionNone of the options..pdfanushkaent7
 
It is a test for iron(III) ion present in the solution , so it is a .pdf
It is a test for iron(III) ion present in the solution , so it is a .pdfIt is a test for iron(III) ion present in the solution , so it is a .pdf
It is a test for iron(III) ion present in the solution , so it is a .pdfanushkaent7
 
C. 12Solution C. 12.pdf
  C.  12Solution  C.  12.pdf  C.  12Solution  C.  12.pdf
C. 12Solution C. 12.pdfanushkaent7
 
I think that y=21SolutionI think that y=21.pdf
I think that y=21SolutionI think that y=21.pdfI think that y=21SolutionI think that y=21.pdf
I think that y=21SolutionI think that y=21.pdfanushkaent7
 
Connects corresponding regions of left and right cerebral hemisphere.pdf
Connects corresponding regions of left and right cerebral hemisphere.pdfConnects corresponding regions of left and right cerebral hemisphere.pdf
Connects corresponding regions of left and right cerebral hemisphere.pdfanushkaent7
 

More from anushkaent7 (20)

A. ASBRThe router is an ASBR type because all configured networks .pdf
A. ASBRThe router is an ASBR type because all configured networks .pdfA. ASBRThe router is an ASBR type because all configured networks .pdf
A. ASBRThe router is an ASBR type because all configured networks .pdf
 
A TetrahedralB polar becaue there is an uneven distribution of e.pdf
A TetrahedralB polar becaue there is an uneven distribution of e.pdfA TetrahedralB polar becaue there is an uneven distribution of e.pdf
A TetrahedralB polar becaue there is an uneven distribution of e.pdf
 
1)Journal entriesT- AccountsCommon StockCommon Stock dividends.pdf
1)Journal entriesT- AccountsCommon StockCommon Stock dividends.pdf1)Journal entriesT- AccountsCommon StockCommon Stock dividends.pdf
1)Journal entriesT- AccountsCommon StockCommon Stock dividends.pdf
 
1) a.Seasonal H1N1 influenza Seasonal contaminate the superior or u.pdf
1) a.Seasonal H1N1 influenza Seasonal contaminate the superior or u.pdf1) a.Seasonal H1N1 influenza Seasonal contaminate the superior or u.pdf
1) a.Seasonal H1N1 influenza Seasonal contaminate the superior or u.pdf
 
1 mole of 12C contains 6.02 x 1023 carbon atomsSolution1 mole .pdf
1 mole of 12C contains 6.02 x 1023 carbon atomsSolution1 mole .pdf1 mole of 12C contains 6.02 x 1023 carbon atomsSolution1 mole .pdf
1 mole of 12C contains 6.02 x 1023 carbon atomsSolution1 mole .pdf
 
(-3,0)Solution(-3,0).pdf
(-3,0)Solution(-3,0).pdf(-3,0)Solution(-3,0).pdf
(-3,0)Solution(-3,0).pdf
 
Two advantages of using financial accounting information in decision.pdf
Two advantages of using financial accounting information in decision.pdfTwo advantages of using financial accounting information in decision.pdf
Two advantages of using financial accounting information in decision.pdf
 
their joint probability is the product of the probability of the eve.pdf
their joint probability is the product of the probability of the eve.pdftheir joint probability is the product of the probability of the eve.pdf
their joint probability is the product of the probability of the eve.pdf
 
The phylogenetic origin of the flu virus that caused the 2009 pandem.pdf
The phylogenetic origin of the flu virus that caused the 2009 pandem.pdfThe phylogenetic origin of the flu virus that caused the 2009 pandem.pdf
The phylogenetic origin of the flu virus that caused the 2009 pandem.pdf
 
The Program to find out the middle of a given linked listclass Lin.pdf
The Program to find out the middle of a given linked listclass Lin.pdfThe Program to find out the middle of a given linked listclass Lin.pdf
The Program to find out the middle of a given linked listclass Lin.pdf
 
Question 1Answer b. The returned value, return address, paramete.pdf
Question 1Answer b. The returned value, return address, paramete.pdfQuestion 1Answer b. The returned value, return address, paramete.pdf
Question 1Answer b. The returned value, return address, paramete.pdf
 
Plasma membrane of human is made of phospholipids; these are fluids .pdf
Plasma membrane of human is made of phospholipids; these are fluids .pdfPlasma membrane of human is made of phospholipids; these are fluids .pdf
Plasma membrane of human is made of phospholipids; these are fluids .pdf
 
Please post the exact proplem in comments.SolutionPlease post .pdf
Please post the exact proplem in comments.SolutionPlease post .pdfPlease post the exact proplem in comments.SolutionPlease post .pdf
Please post the exact proplem in comments.SolutionPlease post .pdf
 
P( both correct) = P( first correct)P( second correct) = 1212 = .pdf
P( both correct) = P( first correct)P( second correct) = 1212 = .pdfP( both correct) = P( first correct)P( second correct) = 1212 = .pdf
P( both correct) = P( first correct)P( second correct) = 1212 = .pdf
 
One of the functions of skin is to regulate the temperature. The ski.pdf
One of the functions of skin is to regulate the temperature. The ski.pdfOne of the functions of skin is to regulate the temperature. The ski.pdf
One of the functions of skin is to regulate the temperature. The ski.pdf
 
None of the options.SolutionNone of the options..pdf
None of the options.SolutionNone of the options..pdfNone of the options.SolutionNone of the options..pdf
None of the options.SolutionNone of the options..pdf
 
It is a test for iron(III) ion present in the solution , so it is a .pdf
It is a test for iron(III) ion present in the solution , so it is a .pdfIt is a test for iron(III) ion present in the solution , so it is a .pdf
It is a test for iron(III) ion present in the solution , so it is a .pdf
 
C. 12Solution C. 12.pdf
  C.  12Solution  C.  12.pdf  C.  12Solution  C.  12.pdf
C. 12Solution C. 12.pdf
 
I think that y=21SolutionI think that y=21.pdf
I think that y=21SolutionI think that y=21.pdfI think that y=21SolutionI think that y=21.pdf
I think that y=21SolutionI think that y=21.pdf
 
Connects corresponding regions of left and right cerebral hemisphere.pdf
Connects corresponding regions of left and right cerebral hemisphere.pdfConnects corresponding regions of left and right cerebral hemisphere.pdf
Connects corresponding regions of left and right cerebral hemisphere.pdf
 

Recently uploaded

POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 

Recently uploaded (20)

POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 

Main class --------------------------import java.awt.FlowLayout.pdf

  • 1. Main class :- ------------------------- import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub final InfixExperssionEvaluator ie = new InfixExperssionEvaluator(); JFrame frame = new JFrame("FrameDemo"); frame.setSize(600,200); frame.setLayout(new FlowLayout()); JPanel main = new JPanel(new GridLayout(3, 1)); JPanel panel1 = new JPanel(new GridLayout(1, 2)); panel1.setSize(500, 250); panel1.add(new JLabel("Enter Infix Expression")); final JTextField field1 = new JTextField(); field1.setSize(150,100); panel1.add(field1); main.add(panel1);
  • 2. JPanel panel2 = new JPanel(new GridLayout(1, 1)); panel1.setSize(300, 150); JButton button = new JButton(); button.setSize(200, 100); button.setText("Submit"); panel2.add(button); main.add(panel2); JPanel panel3 = new JPanel(new GridLayout(1, 2)); panel3.add(new JLabel("Value : ")); final JLabel lbl = new JLabel(); panel3.add(lbl); main.add(panel3); frame.getContentPane().add(main); frame.setVisible(true); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if ("Submit".equals(e.getActionCommand())) { String expr = field1.getText(); lbl.setText(Double.toString(ie.infixToValue(expr))); } } }); button.setActionCommand("Submit"); String expr = "((2*5)+(6/2))"; System.out.println("value is ::"+ ie.infixToValue(expr));
  • 3. } } Class for Evaluate methods :- ----------------------------------------- import java.util.ArrayDeque; import java.util.HashMap; import java.util.Map; import java.util.Stack; import java.util.StringTokenizer; public class InfixExperssionEvaluator { Stack expressionStack = new Stack(); Stack valueStack = new Stack(); //to hold only non-decimal values public static final String OPERATORS="+-/*()"; //ignore the "(" as an operator //Map For Operator precedence Key(+,-,*,/) , value 0/1/2/3.. Map operator_levels = new HashMap(); public InfixExperssionEvaluator(){ operator_levels.put(")", 0); operator_levels.put("*", 1); operator_levels.put("/", 1); operator_levels.put("+", 2); operator_levels.put("-", 2); operator_levels.put("(", 3); } double infixToValue(String inputExpression) { String eachNumber=""; //to hold multiple digit values. lame idea, i know, but can't think of anything else at 2 AM int totalCharInInput = inputExpression.length(); inputExpression.replaceAll("s+",""); //Devide String to Tokens StringTokenizer tokens = new StringTokenizer(inputExpression, "{}()*/+-", true); //Loop through each Token
  • 4. while(tokens.hasMoreTokens()){ String eachChar = tokens.nextToken(); if (isValidOperator(eachChar)){ //We could stack up a lot of left parenthesis in the beginning without reaching a number. Weed it out if (!isLeftParen(eachChar) && isNumeric(eachNumber)){ valueStack.push(Long.parseLong(eachNumber)); //push the till now accumulated number to the value stack eachNumber=""; } if (expressionStack.isEmpty() || isLeftParen(eachChar)){ //first item or left parenthesis expressionStack.push(eachChar); } else if (isRightParen(eachChar)){ evaluateAndPushValueToStackUntilLeftParenthesis(valueStack, expressionStack); } //if the current operator has higher precedence than the first item in the stack, then it is fine. //Just insert the incoming else if (getHigherPrecedenceOperator(eachChar, expressionStack.peek()).equals(eachChar)){ expressionStack.push(eachChar); } //if the current operator is lesser, then the previous higher precedence expression have to be //evaluated. Else, we would be making wrong calculations while popping off for final evaluation else if(valueStack.size() > 2){ //the current operator has higher precedence. Evaluate expression evaluateAndPushValueToValueStack(valueStack, expressionStack); //after evaluation of the higher pair, don't forget to insert the current character into the expression stack expressionStack.push(eachChar);
  • 5. } } else if (isNumeric(eachChar)){ eachNumber+=eachChar; if (totalCharInInput==0){ valueStack.push(Long.parseLong(eachNumber)); //the last element } } System.out.println ("Value Stack : "+valueStack); System.out.println ("Expression Stack : "+expressionStack); } System.out.println("Final Expression stack " +expressionStack); System.out.println("Final Value stack : "+valueStack); while (!expressionStack.empty()){ evaluateAndPushValueToValueStack(valueStack,expressionStack); } System.out.println ("Final value : "+valueStack); return valueStack.pop(); } boolean isRightParen(String operator) { return (operator.equals(")")?true:false); } boolean isLeftParen(String operator) { return (operator.equals("(")?true:false); } //Evaluate and push reslt to value stack private void evaluateAndPushValueToValueStack(Stack valueStack, Stack expressionStack) { Long firstOperand=valueStack.pop(); Long secondOperand=valueStack.pop(); System.out.println ("Value stack : "+firstOperand+ ":"+ secondOperand ); Long evaluatedValue = this.evaluate(secondOperand, firstOperand, expressionStack.pop()); //intermediate result
  • 6. valueStack.push(evaluatedValue); } //Evaluate current statck private void evaluateAndPushValueToStackUntilLeftParenthesis(Stack valueStack, Stack expressionStack) { while (!expressionStack.empty()){ if (isLeftParen(expressionStack.peek())){ //if the left parenthesis has been reached, then pop it up and exit expressionStack.pop(); break; } evaluateAndPushValueToValueStack(valueStack,expressionStack); } } //Caclulate result for 2 oprands and one operator Long evaluate(Long firstOperand, Long secondOperand, String operator) throws ArithmeticException{ Long returnValue = (long) 0; switch (operator) { case "+" : returnValue=firstOperand+secondOperand; break; case "-" : returnValue=firstOperand-secondOperand; break; case "*": returnValue=firstOperand*secondOperand; break; case "/": if (secondOperand==0){ //cheating death by zero returnValue=(long) 0; throw new ArithmeticException("Divide by zero"); } else{
  • 7. returnValue = firstOperand/secondOperand; } break; } return returnValue; } //Check whether String is operator or not boolean isValidOperator(String input) { return (OPERATORS.contains(input)?true:false); } //Check Precedence String getHigherPrecedenceOperator(String firstOperator, String secondOperator){ return (operator_levels.get(firstOperator) < operator_levels.get(secondOperator)?firstOperator:secondOperator); } //Check whether String is number or not public static boolean isNumeric(String str) { return str.matches("-?d+(.d+)?"); //match a number with optional '-' and decimal. } } Solution Main class :- ------------------------- import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton;
  • 8. import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub final InfixExperssionEvaluator ie = new InfixExperssionEvaluator(); JFrame frame = new JFrame("FrameDemo"); frame.setSize(600,200); frame.setLayout(new FlowLayout()); JPanel main = new JPanel(new GridLayout(3, 1)); JPanel panel1 = new JPanel(new GridLayout(1, 2)); panel1.setSize(500, 250); panel1.add(new JLabel("Enter Infix Expression")); final JTextField field1 = new JTextField(); field1.setSize(150,100); panel1.add(field1); main.add(panel1); JPanel panel2 = new JPanel(new GridLayout(1, 1)); panel1.setSize(300, 150); JButton button = new JButton(); button.setSize(200, 100); button.setText("Submit"); panel2.add(button); main.add(panel2);
  • 9. JPanel panel3 = new JPanel(new GridLayout(1, 2)); panel3.add(new JLabel("Value : ")); final JLabel lbl = new JLabel(); panel3.add(lbl); main.add(panel3); frame.getContentPane().add(main); frame.setVisible(true); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if ("Submit".equals(e.getActionCommand())) { String expr = field1.getText(); lbl.setText(Double.toString(ie.infixToValue(expr))); } } }); button.setActionCommand("Submit"); String expr = "((2*5)+(6/2))"; System.out.println("value is ::"+ ie.infixToValue(expr)); } } Class for Evaluate methods :- ----------------------------------------- import java.util.ArrayDeque; import java.util.HashMap; import java.util.Map; import java.util.Stack; import java.util.StringTokenizer;
  • 10. public class InfixExperssionEvaluator { Stack expressionStack = new Stack(); Stack valueStack = new Stack(); //to hold only non-decimal values public static final String OPERATORS="+-/*()"; //ignore the "(" as an operator //Map For Operator precedence Key(+,-,*,/) , value 0/1/2/3.. Map operator_levels = new HashMap(); public InfixExperssionEvaluator(){ operator_levels.put(")", 0); operator_levels.put("*", 1); operator_levels.put("/", 1); operator_levels.put("+", 2); operator_levels.put("-", 2); operator_levels.put("(", 3); } double infixToValue(String inputExpression) { String eachNumber=""; //to hold multiple digit values. lame idea, i know, but can't think of anything else at 2 AM int totalCharInInput = inputExpression.length(); inputExpression.replaceAll("s+",""); //Devide String to Tokens StringTokenizer tokens = new StringTokenizer(inputExpression, "{}()*/+-", true); //Loop through each Token while(tokens.hasMoreTokens()){ String eachChar = tokens.nextToken(); if (isValidOperator(eachChar)){ //We could stack up a lot of left parenthesis in the beginning without reaching a number. Weed it out if (!isLeftParen(eachChar) && isNumeric(eachNumber)){ valueStack.push(Long.parseLong(eachNumber)); //push the till now accumulated number to the value stack eachNumber="";
  • 11. } if (expressionStack.isEmpty() || isLeftParen(eachChar)){ //first item or left parenthesis expressionStack.push(eachChar); } else if (isRightParen(eachChar)){ evaluateAndPushValueToStackUntilLeftParenthesis(valueStack, expressionStack); } //if the current operator has higher precedence than the first item in the stack, then it is fine. //Just insert the incoming else if (getHigherPrecedenceOperator(eachChar, expressionStack.peek()).equals(eachChar)){ expressionStack.push(eachChar); } //if the current operator is lesser, then the previous higher precedence expression have to be //evaluated. Else, we would be making wrong calculations while popping off for final evaluation else if(valueStack.size() > 2){ //the current operator has higher precedence. Evaluate expression evaluateAndPushValueToValueStack(valueStack, expressionStack); //after evaluation of the higher pair, don't forget to insert the current character into the expression stack expressionStack.push(eachChar); } } else if (isNumeric(eachChar)){ eachNumber+=eachChar; if (totalCharInInput==0){ valueStack.push(Long.parseLong(eachNumber)); //the last element } }
  • 12. System.out.println ("Value Stack : "+valueStack); System.out.println ("Expression Stack : "+expressionStack); } System.out.println("Final Expression stack " +expressionStack); System.out.println("Final Value stack : "+valueStack); while (!expressionStack.empty()){ evaluateAndPushValueToValueStack(valueStack,expressionStack); } System.out.println ("Final value : "+valueStack); return valueStack.pop(); } boolean isRightParen(String operator) { return (operator.equals(")")?true:false); } boolean isLeftParen(String operator) { return (operator.equals("(")?true:false); } //Evaluate and push reslt to value stack private void evaluateAndPushValueToValueStack(Stack valueStack, Stack expressionStack) { Long firstOperand=valueStack.pop(); Long secondOperand=valueStack.pop(); System.out.println ("Value stack : "+firstOperand+ ":"+ secondOperand ); Long evaluatedValue = this.evaluate(secondOperand, firstOperand, expressionStack.pop()); //intermediate result valueStack.push(evaluatedValue); } //Evaluate current statck private void evaluateAndPushValueToStackUntilLeftParenthesis(Stack valueStack, Stack expressionStack) { while (!expressionStack.empty()){ if (isLeftParen(expressionStack.peek())){ //if the left parenthesis has been reached, then pop it up and exit expressionStack.pop();
  • 13. break; } evaluateAndPushValueToValueStack(valueStack,expressionStack); } } //Caclulate result for 2 oprands and one operator Long evaluate(Long firstOperand, Long secondOperand, String operator) throws ArithmeticException{ Long returnValue = (long) 0; switch (operator) { case "+" : returnValue=firstOperand+secondOperand; break; case "-" : returnValue=firstOperand-secondOperand; break; case "*": returnValue=firstOperand*secondOperand; break; case "/": if (secondOperand==0){ //cheating death by zero returnValue=(long) 0; throw new ArithmeticException("Divide by zero"); } else{ returnValue = firstOperand/secondOperand; } break; } return returnValue; } //Check whether String is operator or not boolean isValidOperator(String input) { return (OPERATORS.contains(input)?true:false);
  • 14. } //Check Precedence String getHigherPrecedenceOperator(String firstOperator, String secondOperator){ return (operator_levels.get(firstOperator) < operator_levels.get(secondOperator)?firstOperator:secondOperator); } //Check whether String is number or not public static boolean isNumeric(String str) { return str.matches("-?d+(.d+)?"); //match a number with optional '-' and decimal. } }