I'm new in java programming but somehow I understand little especially basic because I have a background in Vb6

I find it difficult because it has lot of java keyword that I dont understand.
Now, I need your help to defend this program in our class. Help me please.
If it is necessary to give an example, Pls include it.

import javax.swing.*;
public class StackArray 
{
    private Object stack[];
    private int sizeIndex = 5;
    private int topPtr;
		
    public StackArray()
    {
        stack = new Object[sizeIndex];	//What is object?
    }
    
    public void push(Object stackItem)
    { 
        if(!isFull())
        {
        	stack[topPtr] = stackItem;	//What is Ptr stands for in topPtr?
        	topPtr++;		// why topPtr++?
        }    
        else
        {
        	JOptionPane.showMessageDialog(null,"Stack is Full!","Error",JOptionPane.ERROR_MESSAGE);

        }      
    }
    
    public Object pop()
    {
    	Object x = null;	  // why x is initially null?
    	if(!isEmpty())
        {
            x = stack[--topPtr];	//Why --topPtr?
            stack[topPtr] = null;
        }
        return x;			//Why we return to x?
    }
    
    public Object top()		//What is ts stands for?
    {	
    	Object ts = null;		//Why null?
        if(!isEmpty())
        {
        	ts = stack[topPtr - 1];	 //Why we subtract 1 from topPtr?
        }
        return ts;  		//why we return to ts?
    }
    
    public boolean isEmpty()
    {
        return topPtr == 0;
    }
    
    public boolean isFull()
    {
		return topPtr == sizeIndex;	 	
    }
  
        
	public boolean contains(Object stackItem)
	{
		 boolean contains = false;	//Why false, not rue?
		 if(!isEmpty())
		 {
		 	for(int i = 0; i < sizeIndex; i++)	//meaning of this
			{
			 if(stack[i].equals(stackItem))
			 {
			 	contains = true;	 //Why true?
				break;
			 }
			}
		 }
		 return contains;		//Why return to contains?
	}
		
    public String toString()	//What is tostring and purpose?
    {
        StringBuffer display = new StringBuffer();	//what is StringBuffer?
        
        display.append("{");	//What is append and purpose of this "{"?
            for(int i = 0; i< sizeIndex; i++)
            {
                if(stack[i] != null)
                {
                    display.append(stack[i]);
                    if( i < topPtr - 1)	//Why we subtract 1
                    {
                        display.append(",");
                    }
                }
            }
        
        display.append("}");
        return display.toString();
    }
}

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

public class Numeral
{
	public static boolean isOperand(String o)	//What is static?
	{	
		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
				{
					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.

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

Recommended Answers

All 2 Replies

Fist of all, as a concept do you know what stack is?
Do you know what this calculates to: + a b?

Stack is a structure where you put items in it one after the other and when you want to remove one you take the last one entered (LIFO). Like a stack of plates. You always take the one on top. Assume that you put letters in the stack:
put a
put b
put c.
Now you stack is like this:
| c |
| b |
| a |
-----
When you want to remove something you can only take c.

When you write + a b, it means a + b. You take the operator '+' and you apply it to the 2 next numbers. If next to the operator there is another operator you apply the next operator to the next 2 numbers and so on:

* - a b + c d
* - a b + c d
* (a-b) + c d
* (a-b) + c d
* (a-b) (c+d)
(a-b) * (c+d)

The whole concept is you put things in the stack and if they are digits or '+' you either add more or you remove to calculate:

Example:
* - a b + c d

>is d number?
>put d
>is c number?
>put c

>is + operator?
>remove 2 from the stack (when you remove things from stack you always take the top 2 so you will take c and d).
> apply + to the ones removed and you get (c+d). Now (c+d) is a number you put in the stack

>put (c+d). Actually what you put is the result of the addition.
>is b number?
>put b
>is a number?
>put a

>is - operator?
>remove 2 from the stack (when you remove things from stack you always take the top 2 so you will take a and b).
> apply - to the ones removed and you get (a-b). Now (a-b) is a number you put in the stack

>put (a-b). Actually what you put is the result of the subtraction.

>is * operator?
>remove 2 from the stack (when you remove things from stack you always take the top 2 so you will take the results of the previous calculations: (a-b) and (c+d)).
> apply * to the ones removed and you get ((a-b) * (c+d)). Now you have another result and you put it in the stack

>finished with the input.
>take the result from the stack

Try to understand this, because there is no point in explaining what the code does if you don't know why it does it. I will write a new post about the code.

If someone can explained it better please try

PS. If you play Magic The Gathering, the stack in the game and the stack described here are the same.

import javax.swing.*;
public class StackArray 
{
    private Object stack[];
    private int sizeIndex = 5;
    private int topPtr;
		
    public StackArray()
    {
        stack = new Object[sizeIndex];	//What is object?
/*As in VB6.NET everything is an Object (everything extends from Object). You create an array that will contain Objects and since everything is an Object you can put whatever you want inside it*/
    }
    
    public void push(Object stackItem)
    { 
        if(!isFull())
        {
        	stack[topPtr] = stackItem;	//What is Ptr stands for in topPtr?
        	topPtr++;		// why topPtr++?
/*
You use the int(eger) variable topPtr to point (nothing to do with C pointers) where the new element needs to be put in  the stack. You put a new item (stackItem) and you increase topPtr by one, because the new element will be put after the last one. Also the code checks if the stack (array) is full because since you simulate the stack with an array you can put unlimited things in the array.
*/
        }    
        else
        {
        	JOptionPane.showMessageDialog(null,"Stack is Full!","Error",JOptionPane.ERROR_MESSAGE);

        }      
    }
    
    public Object pop()
    {
    	Object x = null;	  // why x is initially null?
//You set it an initial value. If there is nothing in the stack then you will return nothing
    	if(!isEmpty())
        {
            x = stack[--topPtr];	//Why --topPtr?
            stack[topPtr] = null;
/*
Because topPtr determines where the next element will be put. So you since you want to remove the last element you decrease topPtr by one to take the last element. Also by decreasing you make sure a new element will be put in its place.
*/
        }
        return x;			//Why we return to x?
//because you HAVE to return what you removed
    }
    
    public Object top()		//What is ts stands for?
    {	
    	Object ts = null;		//Why null?
        if(!isEmpty())
        {
        	ts = stack[topPtr - 1];	 //Why we subtract 1 from topPtr?
//the same as above, with the difference is that you don't remove, but simply you want to "see" and return the top element of the stack, not remove it. And you DON'T subtract 1 from topPtr. You don't change its value. The previous method changed topPtr's value (--toPtr) this one simply takes what was last entered and since topPtr shows where the next will be put you take what is before topPtr.
        }
        return ts;  		//why we return to ts?
    }
    
    public boolean isEmpty()
    {
        return topPtr == 0;
    }
    
    public boolean isFull()
    {
		return topPtr == sizeIndex;	 	
    }
  
        
	public boolean contains(Object stackItem)
	{
		 boolean contains = false;	//Why false, not rue?
		 if(!isEmpty())
		 {
		 	for(int i = 0; i < sizeIndex; i++)	//meaning of this
//it is a classic for-loop that reads the array. If it finds the item contains becomes true. If //not you return what was already set to contains: false. That is why you initialize it with //false. So it will return false, if its value doesn't change in the if statement 
			{
			 if(stack[i].equals(stackItem))
			 {
			 	contains = true;	 //Why true?
				break;
			 }
			}
		 }
		 return contains;		//Why return to contains?
	}
		
//the purpose is to return all the elements of the array as one string separated by a comma //','
//because concatenating a lot of strings is not efficient the StringBuffer class is used. The append concatenates Strings
    public String toString()	//What is tostring and purpose?
    {
        StringBuffer display = new StringBuffer();	//what is StringBuffer?
        
        display.append("{");	//What is append and purpose of this "{"? it simply adds the { at the begining of the result
            for(int i = 0; i< sizeIndex; i++)
            {
                if(stack[i] != null)
                {
                    display.append(stack[i]);
                    if( i < topPtr - 1)	//Why we subtract 1
//you DON'T subtract. you check if the value of i is 1 less than the topPtr in order to add the comma that seperates the elements of the array
                    {
                        display.append(",");
                    }
                }
            }
        
        display.append("}");
        return display.toString();
//you return what was concatenated in the display variable
    }
}

Watch my comments

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.