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.
}
}