import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ExpressionCalculator implements KeyListener
{
	private JFrame frame;
	private JLabel label;
	private JPanel boxLayout,panel0,panel1,panel2,panel3;
	private JTextField TxtInfix,TxtPostfix,TxtPrefix,TxtResult;
	
	private Font font;
		
	public ExpressionCalculator()
	{
		boxLayout = new JPanel();
		
		font = new Font("Serif",Font.BOLD,12);
		
		//For infix notation
		panel0 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,0));
		panel0.add(label = new JLabel("Infix :"));
		panel0.add(TxtInfix = new JTextField("",15));
		
		label.setFont(font);
		
		label.setPreferredSize(new Dimension(49,16));
		label.setHorizontalAlignment(JLabel.RIGHT);
		
		//KeyListener
		TxtInfix.addKeyListener(this);
		
		//For postfix notation
		panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,0));
		panel1.add(label = new JLabel("Postfix :"));
		panel1.add(TxtPostfix = new JTextField("",15));
		
		label.setFont(font);
		label.setPreferredSize(new Dimension(49,16));
		label.setHorizontalAlignment(JLabel.RIGHT);
		
		TxtPostfix.addKeyListener(this);
		
		//For the result of postfix evaluatro
		panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,0));
		panel2.add(label = new JLabel("Prefix :"));
		panel2.add(TxtPrefix = new JTextField("",15));
		
		label.setFont(font);
		label.setPreferredSize(new Dimension(49,16));
		label.setHorizontalAlignment(JLabel.RIGHT);
		
		panel3 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,0));
		panel3.add(label = new JLabel("Result :"));
		panel3.add(TxtResult = new JTextField("",15));
		
		label.setFont(font);
		label.setForeground(Color.RED);
		label.setPreferredSize(new Dimension(49,16));
		label.setHorizontalAlignment(JLabel.RIGHT);
		
		TxtResult.setFocusable(false);
	}
	
	public Container createContent()
	{
		boxLayout.setLayout(new BoxLayout(boxLayout, 
								BoxLayout.PAGE_AXIS));
		
		boxLayout.setOpaque(true);
				  
		boxLayout.add(panel0);
		boxLayout.add(Box.createRigidArea(new Dimension(0,5)));
		boxLayout.add(panel1);
		boxLayout.add(Box.createRigidArea(new Dimension(0,5)));
		boxLayout.add(panel2);
		boxLayout.add(Box.createRigidArea(new Dimension(0,5)));
		boxLayout.add(panel3);
		boxLayout.add(Box.createRigidArea(new Dimension(0,5)));
	
		boxLayout.setBorder(BorderFactory.createTitledBorder("Notations"));
		
		JPanel layoutPanel = new JPanel();	
		
		layoutPanel.add(boxLayout);
		
		return layoutPanel;
	}
	
	public void keyPressed(KeyEvent e)
	{
		Object source = e.getSource();
		String keyText = e.getKeyText(e.getKeyCode());
		
		if(source.equals(TxtInfix))
		{
			if(keyText.equals("Enter"))
			{
				String notation;
			
				notation  = new String(TxtInfix.getText());
			
				PostfixNotation i;
				i = new PostfixNotation(notation);
			
				TxtPostfix.setText(i.postfixNotation());
				
				PrefixNotation n;
				n = new PrefixNotation(notation);
			
				TxtPrefix.setText(n.prefixNotation());
			
				PostfixEvaluator p; 
				p = new PostfixEvaluator(TxtPostfix.getText());
			
				TxtResult.setText(p.getResult());
			}
		}
		else if(source.equals(TxtPostfix))
		{
			if(keyText.equals("Enter"))
			{
				PostfixEvaluator p; 
				p = new PostfixEvaluator(TxtPostfix.getText());
			
				TxtResult.setText(p.getResult());	
			}
		}
	}
	
	public void keyReleased(KeyEvent e){}
	public void keyTyped(KeyEvent e){}
	
	public void showGUI()
	{
		
		frame = new JFrame("Expression Calculator");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(createContent());
				
		frame.pack();
		frame.setVisible(true);
		frame.setResizable(false);		
	}
	
	public static void main(String[] args)
	{
		Runnable doRun = new Runnable(){
				public void run()
				{
					new ExpressionCalculator().showGUI();
				}
			};
		javax.swing.SwingUtilities.invokeLater(doRun);
	}
}
public class MyException extends Exception
{
	public MyException(String msg)
	{
		System.out.println(msg);
	}
}
public class Numeral
{
	public static boolean isOperand(String o)
	{	
		boolean operand = true;
			for(int i = 0; i < o.length(); i++)
			{
				char c = o.charAt(i);
				if(!Character.isDigit(c))
				{
					operand = false;
					break;
				}	
			}
		return operand;
	}
	
	public static boolean isOperator(String o)
	{
		return(o.equals("+") || o.equals("*") || 
		       o.equals("-") || o.equals("/"));
	}
}
import java.util.*;

public class PostfixEvaluator
{
	StackArray stack;
	StringTokenizer st;

	private int val1,val2;
	private int result;

	public PostfixEvaluator(String postfix)
	{
		stack = new StackArray();

		st = new StringTokenizer(postfix);

		while(st.hasMoreElements())
		{
			String token = st.nextToken();
			if(Numeral.isOperand(token))
			{
				stack.push(token);
			}
			else if(Numeral.isOperator(token))
			{
				if(token.equals("+"))
				{
					val1 = Integer.parseInt(stack.pop().toString());
					val2 = Integer.parseInt(stack.pop().toString());

					result = val1 + val2;

					stack.push(new Integer(result));
				}
				else if(token.equals("-"))
				{
					val1 = Integer.parseInt(stack.pop().toString());
					val2 = Integer.parseInt(stack.pop().toString());

					result = val2 - val1;

					stack.push(new Integer(result));
				}
				else if(token.equals("*"))
				{
					val1 = Integer.parseInt(stack.pop().toString());
					val2 = Integer.parseInt(stack.pop().toString());

					result = val1 * val2;

					stack.push(new Integer(result));
				}
				else if(token.equals("/"))
				{
					val1 = Integer.parseInt(stack.pop().toString());
					val2 = Integer.parseInt(stack.pop().toString());

					result = val2 / val1;

					stack.push(new Integer(result));
				}
			}
		}
	}

	public String getResult()
	{
		return String.valueOf(stack.top());
	}
}
import java.util.*;
import javax.swing.JOptionPane;

public class PostfixNotation
{
	private StackArray stack;
	private StringTokenizer st;
	private StringBuffer postfix = new StringBuffer();
		
	public PostfixNotation(String infix)
	{
		convert(infix);
	}
	
	public void convert(String infix)
	{
		stack = new StackArray();
				
		st = new StringTokenizer(infix);
		
		while(st.hasMoreElements())
		{
			String token = st.nextToken();
			
			if(Numeral.isOperand(token))
			{
				toPostfix(token);
			}
			
			else if(Numeral.isOperator(token))
			{
				 if(!stack.isEmpty())
				 {	
					if(Priority.icp(token) < Priority.isp(String.valueOf(stack.top())))
					{
						while(!stack.isEmpty())
						{
							toPostfix(String.valueOf(stack.pop()));
						}
					
						stack.push(token);
					}
					else if(Priority.icp(token) > Priority.isp(String.valueOf(stack.top())))
					{
						stack.push(token);
					}
				 }
				 else
				 {
					stack.push(token);
				 }
			}
			else
			{
				JOptionPane.showMessageDialog(null,"Invalid");
				break;		
			}

			if(!st.hasMoreTokens())
			{
				while(!stack.isEmpty())
				{
					toPostfix(String.valueOf(stack.pop()));
				}
			}	
		}		
	}
	
	public void toPostfix(String token)
	{
		postfix.append(token);
		postfix.insert(postfix.length()," ");
	}
	
	public String postfixNotation()
	{
		return postfix.toString();
	}
}
import java.util.*;

public class PrefixNotation
{
	private StackArray stack;
	
	private StringTokenizer st;
	
	private StringBuffer prefix = new StringBuffer();
	private String[] tokenOfArray = new String[50];
	
	private int topPtr;
	
	public PrefixNotation(String infix)
	{
		convert(infix);
	}
	
	public void convert(String infix)
	{
		stack = new StackArray();
			
		st = new StringTokenizer(infix);
		
		while(st.hasMoreElements())
		{
			String token = st.nextToken();
			tokenOfArray[topPtr++] = token;
		}
	
		while(topPtr > 0)
		{
			--topPtr;
			
			if(Numeral.isOperand(tokenOfArray[topPtr]))
			{
				toPostfix(tokenOfArray[topPtr]);
			}
			
			else if(Numeral.isOperator(tokenOfArray[topPtr]))
			{
				if(!stack.isEmpty())
				{
					if(Priority.icp(tokenOfArray[topPtr]) < Priority.isp(String.valueOf(stack.top())))
					{
						toPostfix(String.valueOf(stack.pop()));
					
						stack.push(tokenOfArray[topPtr]);
					}
					else if(Priority.icp(tokenOfArray[topPtr]) > Priority.isp(String.valueOf(stack.top())))
					{
						stack.push(tokenOfArray[topPtr]);
					}
				}
				else
				{
					stack.push(tokenOfArray[topPtr]);
				}
			}
		}
		
		if(topPtr == 0)
		{
			while(!stack.isEmpty())
			{
				toPostfix(String.valueOf(stack.pop()));	
			}
		}
	}
	
	//display
	public void toPostfix(String token)
	{	
		int offset = 0;
		prefix.insert(offset--,token.concat(" "));
	}
	
	public String prefixNotation()
	{
		return prefix.toString();
	}
}
public class Priority
{
	public static int icp(String x)
	{
		int priority = 0;
		
		if(x.equals("+") || x.equals("-"))
		{
			priority = 1;
		}
		else if(x.equals("/") || x.equals("*"))
		{
			priority = 3;
		}
		
		return priority;
	}
	
	public static int isp(String x)
	{
		int priority = 0;
		
		if(x.equals("+") || x.equals("-"))
		{
			priority = 2;	
		}
		else if(x.equals("/") || x.equals("*"))
		{
			priority = 4;
		}
		
		return priority;
	}
}
public class Reverse
{
	public StringBuffer rev;
	public String[]		arr;
	public int	  		len;
	public int			ptr;
	
	public String 		wrd;
	
	public Reverse(String word)
	{
		arr = new String[100];
		wrd = word;
		
		split(wrd);
	}
	
	public void split(String word)
	{
		int  offset    = 0;
		char space 	   = ' ';
		
		for(int i = 0; i < word.length() - 1; i++)
		{
			if(word.charAt(i) == space)
			{
				arr[ptr++] = word.substring(offset,i);
				offset = i;
			}
		}
		
		//last word to store into array
		arr[ptr++] = word.substring(offset,(word.length()));
	}
		
	public String reverse()
	{
		rev = new StringBuffer();
		
		for(int i = 0; i < ptr ; i++)
		{
			String token = arr[i].trim();
			len = token.length();
			
			while(len > 0)
			{
				rev.append(token.charAt(--len));
			}
			
			rev.insert(rev.length()," ");	
		}
		
		return rev.toString();
	}
	
	public static void main(String[] args)
	{
		Reverse p = new Reverse("pare");
		
		System.out.println(p.reverse());
		System.out.println("\n");

	
	}
}
public interface Stack
{
	public void push(Object item);
  	public Object pop();
  	public Object top();
  	public boolean isEmpty();
  	public boolean isFull();
  	public void clear();  
}
public class StackArray implements Stack
{
    private Object stack[];
    private int sizeIndex = 100;
    private int topPtr;
		
    public StackArray()
    {
        stack = new Object[sizeIndex];
    }
    
    public void push(Object stackItem)
    { 
        if(!isFull())
        {
        	stack[topPtr] = stackItem;
        	topPtr++;
        }     
    }
    
    public Object pop()
    {
    	Object x = null;
    	if(!isEmpty())
        {
            x = stack[--topPtr];
            stack[topPtr] = null;
        }
        return x;
    }
    
    public Object top()
    {	
    	Object ts = null;
        if(!isEmpty())
        {
        	ts = stack[topPtr - 1];
        }
        return ts;  
    }
    
    public boolean isEmpty()
    {
        return topPtr == 0;
    }
    
    public boolean isFull()
    {
		return topPtr == sizeIndex;	 	
    }
    
    public void clear()
    {
     	for(int i =0; i < sizeIndex; i++)
        {
            stack[i] = null;
			topPtr--;
        }
    }
        
	public boolean contains(Object stackItem)
	{
		 boolean contains = false;
		 if(!isEmpty())
		 {
		 	for(int i = 0; i < sizeIndex; i++)
			{
			 if(stack[i].equals(stackItem))
			 {
			 	contains = true;
				break;
			 }
			}
		 }
		 return contains;
	}
		
    public String toString()
    {
        StringBuffer display = new StringBuffer();
        
        display.append("{");
            for(int i = 0; i< sizeIndex; i++)
            {
                if(stack[i] != null)
                {
                    display.append(stack[i]);
                    if( i < topPtr - 1)
                    {
                        display.append(",");
                    }
                }
            }
        
        display.append("}");
        return display.toString();
    }
}

Hi! Guys I'm back again and need some help for us.

I'm One that Requesting a Calculator Expression before. and now I'm Here That need your help. I have code above that you can see, that code is something downloaded from other site that can i combined of my Idea, They Other code is from a pscode.com, but that program is proven and tested, When I try in my JCreator Language..

This Calculator Expression for MDAS rules, Can you help me or share your about the PEMDAS and unary function. My problem is How to organize the parenthesis , Exponent and Unary code in my downloaded codes and copy paste. I'm beginners but I'm tying my best to do that in that insertion of the codes. If you want to help me. <SNIP> post your suggestion and comments here.

<SNIP>

Thanks.

hi again... here is something that may help:

expression =  term && (plusterm || minusterm)*
plusterm = '+' && term
minusterm = '-' && term
term = factor && (timesfactor || dividefactor)*
timesfactor = '*' && factor
dividefactor = '/' && factor
factor = phrase && (expfactor || phrase)
expfactor= '^' && factor
phrase = '(' && expression && ')' || number

here * at the end means 0 or more repeats && means an ordered series

it's just the grammar for arithmetic

In the future, please post your question before the wall of code, so people don't have to scroll past it all before they even know what you are asking about.

In the future, please post your question before the wall of code, so people don't have to scroll past it all before they even know what you are asking about.

Ezzaral, thanks for the Suggestion.

But My question is understand in above in my post it's clearly and soft, Unary, parenthesis and Exponent. The code that can i post in above is proven and tested of MDAS rules, but i need to used in a PEMDAS rules..

i suggest you read this thread

that thread was can't be my code now, i know the code before that can I post is Expression Calculator, bu I can't solve it.. I think that thread was deleted by the admin.


Sorry.

This article has been dead for over six months. Start a new discussion instead.