I try add this code(below) after "else if(token.equals("*"))" in PostfixEvaluator.java but it doesn't work like exponent. Can you help me to figure it out what is the right code for exponent.

else if(token.equals("^"))
{
	val1 = Integer.parseInt(stack.pop().toString());
	val2 = Integer.parseInt(stack.pop().toString());

	result = val2 ^ val1;

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

And lastly, Can you point to me which part of the code where I can see the code in "spacing",
like: 1_2_3_*_+ where "_" is spacing or simply 1 2 3 * +.
Why the program understands the spacing? Which part of the code?

Thanks for reading...


Here's the entire code:

import javax.swing.*;

public class StackArray 
{
    private Object stack[];
    private int sizeIndex = 5;
    private int topPtr;
		
    public StackArray()
    {
        stack = new Object[sizeIndex];	
    }
    
    public void push(Object stackItem)
    { 
        if(!isFull())
        {
        	stack[topPtr] = stackItem;
        	topPtr++;					
        }    
        else
        {
        	JOptionPane.showMessageDialog(null,"Stack is Full!","Error",JOptionPane.ERROR_MESSAGE);

        }      
    }
    
    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 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();
    }
}

=========================================

public class Numeral
{
	public static boolean isOperand(String o)	
	{	
		boolean operand = true;	//why boolean and why true?
			for(int i = 0; i < o.length(); i++)  //purpose of this: Why o.length and i++? 
			{
				char c = o.charAt(i);			
				if(!Character.isDigit(c))  //purpose of this and how to read this?
				{
					operand = false;  //Why operand is false?
					break;
				}	
			}
		return operand;	 //Why return to operand?
	}
 
	public static boolean isOperator(String o)
	{
		return(o.equals("+") || o.equals("*") ||   //Why return to this?
		       o.equals("-") || o.equals("/"));
	}
}

==========================================

import javax.swing.*;
import java.util.*;

public class PostfixEvaluator
{
	
	StackArray 	stack = new StackArray();
	StringTokenizer tok;

	private int val1,val2;
	private int result;

	public PostfixEvaluator(String postfix)
	{
	tok = new StringTokenizer(postfix);

		while(tok.hasMoreElements())
		{
			String token = tok.nextToken();
			if(Numeral.isOperand(token))
			{
				stack.push(token);
			}
			
			else if (token.equals("a") || token.equals("b") || token.equals("c"))	
			{
				JOptionPane.showMessageDialog(null,"Invalid Input","Error",JOptionPane.ERROR_MESSAGE);
			}
			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());
	}
}

===========================================


This is the runner.

This is the runner.





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

public class Postfix
{
		
JTextField TxtPostfix = new JTextField(15);
JTextField TxtResult = new JTextField(15);

private String inputString = null;
	private JFrame frame;
	private JLabel label;
	private JPanel boxLayout,panel1,panel2,panel3;

	JButton eval = new JButton("Evaluate");
	JButton clear = new JButton("Clear");
	JButton sample = new JButton("Ex. 2 3 4 * + ");
	
	private Font font;
		
	public Postfix()
	{
		boxLayout = new JPanel();

		font = new Font("Serif",Font.BOLD,12);
			
		//For postfix notation
		panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,0));
		panel1.add(label = new JLabel("Postfix : "));
		panel1.add(TxtPostfix);
	
		
		label.setFont(font);
		label.setPreferredSize(new Dimension(49,16));
		label.setHorizontalAlignment(JLabel.RIGHT);
	
		
		panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,0));
		panel2.add(label = new JLabel("Result : "));
		panel2.add(TxtResult);
		
		panel3 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,0));
		panel3.add(eval);
		panel3.add(clear);
		panel3.add(sample);
		
		
		label.setFont(font);
		label.setForeground(Color.red);
		label.setPreferredSize(new Dimension(49,16));
		label.setHorizontalAlignment(JLabel.RIGHT);
		
		TxtResult.setEditable(false);
	}
	
	public Container createContent()
	{
				
		eval.addActionListener ( new ActionListener () {
					public void actionPerformed ( ActionEvent e) {
						
		 		PostfixEvaluator p; 
				p = new PostfixEvaluator(TxtPostfix.getText());				
				
				TxtResult.setText(p.getResult());
					
					}
				});
		
		clear.addActionListener ( new ActionListener () {
					public void actionPerformed ( ActionEvent e) {
						TxtPostfix.setText("");
						TxtResult.setText("");
						
					}
				});
		
		sample.addActionListener ( new ActionListener () {
					public void actionPerformed ( ActionEvent e) {
						TxtPostfix.setText("2 3 4 * +");
						
						
					}
				});		

		
		boxLayout.setOpaque(true);
				  		
		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)));
	
				
		JPanel layoutPanel = new JPanel();	
		
		layoutPanel.add(boxLayout);
		
		return layoutPanel;
	}	
	
	public void showGUI()
	{
		
		frame = new JFrame("Midterm Project");
		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 Postfix().showGUI();
				}
			};
		javax.swing.SwingUtilities.invokeLater(doRun);
	}
	
	
}

Hi ocreds,

In order to raise a number to a certain power, you need to use the Math.pow(double, double) method. The documentation on it is found here in the Math class. Basically it accepts two numbers as parameters and returns the first number raised to the power of the second number. Notice that they are doubles though - I'll leave it up to you to figure out how to use that method with integers.

I'm not sure what you mean by your spacing question, maybe someone else can answer that one.

Just to provide direct link to Math.pow() method as mentioned by darkang

Ah, thanks peter - my mistake!

No mistake, you pointed in right direction and that matters :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.