4 Replies - 372 Views - Last Post: 01 December 2012 - 02:32 PM Rate Topic: -----

#1 mbilal1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 20-September 12

Question about combining two programs, Java Calulator using Stacks.

Posted 29 November 2012 - 01:21 PM

Okay so my assignment was to make a calculator using Stack implementation. It needs to add, subtract, multiply, divide. It needs to have a GUI, and two panels, one which is display, and other is the buttons. After an expression is entered, its postfix or prefix is displayed and then the result. Okay so I am done with the GUI code. I figured out how to make a calculator and it worked, but it doesn't use Stacks. I found this code on a website which used stacks to make a calculator but didn't use stacks. I guess my question is how would i put these two codes together? Any advice anyone can offer would me would be very helpful.

here is the code to the GUI part that i made, along with the calculator that works but doesn't use Stacks
 
import java.awt.*;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.*;
import java.util.*;
public class Calculate extends JFrame implements ActionListener {
    //                                                    10  11  12  13  14  15  16  17   18
       String numbers[]={"0","1","2","3","4","5","6","7","8","9","+","-","*","/",".","CE","C","=","+/-"};
    JButton button[]=new JButton[19];
    Panel p[]=new Panel[6];
    TextField text;
    Box box;
    FlowLayout fv;
       Calculate(String title)
    {
           super(title);
           this.setDefaultCloseOperation(EXIT_ON_CLOSE);
           box=Box.createVerticalBox();
           fv=new FlowLayout();
           fv.setVgap(20);

         this.setLocationRelativeTo(null);       
           for(int i=0;i<numbers.length;i++)
           {
                  button[i]=new JButton(numbers[i]);
                  button[i].addActionListener(this);
                  if(i!=15&&i!=16)
                  {
                         button[i].setPreferredSize(new Dimension(55,35));
                  }
                  else
                  {
                           button[i].setPreferredSize(new Dimension(85,35));
                  }
                  if(i<6)
                  {
                         p[i]=new Panel();
                         box.add(p[i]);
                  }
                  if(i==0)
                  {
                         text=new TextField("0",30);
                         p[0].add(text);
                  }
           }
           p[1].add(button[7]);p[1].add(button[8]);p[1].add(button[9]);p[1].add(button[10]);
           p[2].add(button[4]);p[2].add(button[5]);p[2].add(button[6]);p[2].add(button[11]);
           p[3].add(button[1]);p[3].add(button[2]);p[3].add(button[3]);p[3].add(button[12]);
           p[4].add(button[0]);p[4].add(button[14]);p[4].add(button[18]);p[4].add(button[13]);
           p[5].add(button[15]);p[5].add(button[16]);p[5].add(button[17]);
           this.add(box);
           this.setBounds(520,200,280,320);
           this.setResizable(false);
           this.setVisible(true);
           this.validate();
    }
       int press=0;                            
       int press1=0;                          
       int press2=0;                           
       int strlen=0;                           
       StringBuffer str=new StringBuffer("0"); 
       StringBuffer str2=new StringBuffer("0"); 
       double sum1=0;                          
       public void actionPerformed(ActionEvent e) {
     if(e.getSource()==button[10])             
        {
            this.yunsf(10);
        }
     if(e.getSource()==button[11])             
        {
            this.yunsf(11);
        }
        if(e.getSource()==button[12])             
     {
               this.yunsf(12);
        }
        if(e.getSource()==button[13])             
        {
        this.yunsf(13);
        }   
        if(e.getSource()==button[14])             
        {
               if(str.charAt(str.length()-1)!='+'&&str.charAt(str.length()-1)!='-'&&str.charAt(str.length()-1)!='*'&&str.charAt(str.length()-1)!='/'&&press!=1)
               {
                      str.append(button[14].getText());
                      str2.append(button[14].getText());
                      text.setText(str.toString());
                      press=1;
               }
        }
        if(e.getSource()==button[18])             
        {
               if(str.charAt(str.length()-1)!='+'&&str.charAt(str.length()-1)!='-'&&str.charAt(str.length()-1)!='*'&&str.charAt(str.length()-1)!='/')
               {
                      if(press2==0)
                      {
                             str.insert(strlen, "-");
                             str2.insert(strlen, "@");               
                             text.setText(str.toString());
                             press2=1;
                      }
                      else
                      {
                             str.deleteCharAt(strlen);
                             str2.deleteCharAt(strlen);
                             text.setText(str.toString());
                             press2=0;
                      }
               }
        }
        if(e.getSource()==button[15])             
        {
               if(strlen!=0)
               {
                 str.delete(strlen, str.length());
                 str2.delete(strlen, str2.length());
                 text.setText(str.toString());
               }
               else
               {
                      str.delete(0,str.length());
                      str2.delete(0,str2.length());
                      str.append("0");
                      str2.append("0");
                      text.setText(str.toString());
                      press=0;
                      press2=0;
               }
        }
        if(e.getSource()==button[16])            
     {
             str.delete(0, str.length());
             str2.delete(0, str2.length());
              str.append("0");
              str2.append("0");
              text.setText(str.toString());
              press=0;
              press1=0;
              press2=0;
              strlen=0;
        }
        if(e.getSource()==button[17])             
        {
               if(str.charAt(str.length()-1)!='+'&&str.charAt(str.length()-1)!='-'&&str.charAt(str.length()-1)!='*'&&str.charAt(str.length()-1)!='/'&&press!=1)
               {
                     String txt=str2.toString();
                  String shu[]=txt.split("\\+|\\-|\\*|\\/");    
                  String fh[]=txt.split("@\\d+\\\56\\d+|@\\d+|\\d+\\\56\\d+|\\d+");   
                  for(int i=0;i<shu.length;i++)
                  {
                         if(shu[i].startsWith("@"))
                         {
                                shu[i]="-"+shu[i].substring(1);                             
                         }
                  }
                  calculate(shu,fh);       
               }
        }
        if(e.getSource()==button[0])
        {
               this.shuzi(0);
        }
        if(e.getSource()==button[1])
        {
               this.shuzi(1);
        }
        if(e.getSource()==button[2])
        {
               this.shuzi(2);
        }
        if(e.getSource()==button[3])
        {
               this.shuzi(3);
        }
        if(e.getSource()==button[4])
        {
               this.shuzi(4);
        }
        if(e.getSource()==button[5])
        {
               this.shuzi(5);
        }
        if(e.getSource()==button[6])
        {
               this.shuzi(6);
        }
        if(e.getSource()==button[7])
        {
               this.shuzi(7);
        }
        if(e.getSource()==button[8])
        {
               this.shuzi(8);
        }
        if(e.getSource()==button[9])
        {
         this.shuzi(9);
        }
      
       }
       public void yunsf(int i)          
       {
               if(str.charAt(str.length()-1)!='+'&&str.charAt(str.length()-1)!='-'&&str.charAt(str.length()-1)!='*'&&str.charAt(str.length()-1)!='/'&&str.charAt(str.length()-1)!='.')    
               {
                      str.append(button[i].getText());
                      str2.append(button[i].getText());
                      text.setText(str.toString());
                      press=0;
                      press1=1;
                      press2=0;
                      strlen=str.length();
               }
       }
    public void shuzi(int i)          
    {
          if(press1!=1&&press!=1&&str.charAt(0)=='0')
               {
                      str.replace(0, 1,button[i].getText());
                      str2.replace(0, 1,button[i].getText());
                   text.setText(str.toString());
               }
               else
               {
                      str.append(button[i].getText());
                      str2.append(button[i].getText());
                      text.setText(str.toString());
               }   
    }
       public void calculate(String shu[],String fh[])  
       {
              for(int i=1;i<fh.length;i++)
              {
                     if(fh[i].equals("*"))
                     {
                            double sum=0;
                            sum=Double.parseDouble(shu[i-1])*Double.parseDouble(shu[i]);
                            shu[i-1]=Double.toString(0);
                            shu[i]=Double.toString(sum);
                            fh[i]="#";                           
                     }
                     if(fh[i].equals("/"))
                     {
                            double sum=0;
                            sum=Double.parseDouble(shu[i-1])/Double.parseDouble(shu[i]);
                            shu[i-1]=Double.toString(0);
                            shu[i]=Double.toString(sum);
                            fh[i]="#";                           
                     }
              }
              for(int i=1;i<fh.length;i++)
              {
                     if(fh[i].equals("-"))
                     {
                            double sum=0;
                            int n=i;
                            for(int j=i;j<fh.length;j++)
                            {
                                   if(fh[j].equals("#"))
                                   {
                                          n++;
                                   }
                            }
                            sum=Double.parseDouble(shu[i-1])-Double.parseDouble(shu[n]);
                            shu[i-1]=Double.toString(0);
                            shu[n]=Double.toString(sum);
                            fh[i]="+";
                     }
              }
              sum1=Double.parseDouble(shu[0]);
              for(int i=1;i<shu.length;i++)
              {
                  sum1+=Double.parseDouble(shu[i]);
              }           
              text.setText(Double.toString(sum1));   
              str.delete(0, str.length());
              str.append(text.getText());
              strlen=0;
              str2.delete(0, str2.length());
              str2.append(text.getText());
              press2=0;
       }
       public static void main(String args[])
       {
              Calculate cal=new Calculate("1");
       }
}
	



And here is the Calculator I stumbled on that uses Stacks but doesn't use GUI

   import java.util.*;

    public class rpnCalc
   {
       public static void main(String[] Args)
      {
         String str;
         String[] tokens;
         double result;
         Stack<Double> operands = new Stack();
         Stack<String> operators = new Stack();
         Scanner kb = new Scanner(System.in);
      //initialize varables
         str = "";
         result = 0;
      	
         System.out.print("Enter a simple expression,\nSeparate pieces with a space, example: 12 + 96, or 12 96 + \nPress q to exit\n");
         System.out.println("All expressions are evaluated from RIGHT to LEFT.");
         while(!str.equals("q"))
         { 
            str = kb.nextLine(); //using the keyboard you enter the equation 
            tokens = str.split("\\s+"); //splits what you typed in. 
         
            fillStacks(operands,operators,tokens);
            
            result = calculate(operands,operators);
            
            System.out.println(result + "\nAnother Expression? (q to quit)"); 
         } // end while
         System.out.println("Thanks! Bye now!");      
      }//end main
    	
   /** Methods for Addition, Subtraction, Multiplication and Division */
       private static double add(Stack<Double> stk)
      {
         double op2 = stk.pop();
         double op1 = stk.pop();
         double result = op1 + op2;
         stk.push(result);
         return result;
      }// end add
      
       private static double subtract(Stack<Double> stk)
      {
         double op2 = stk.pop();
         double op1 = stk.pop();
         double result = op1 - op2;
         stk.push(result);
         return result;
      }// end subtract
      
       private static double divide(Stack<Double> stk)
      {
         double op2 = stk.pop();
         double op1 = stk.pop();
         double result = op1 / op2;
         stk.push(result);
         return result;
      }//end divide
   	
       private static double multiply(Stack<Double> stk)
      {
         double op2 = stk.pop();
         double op1 = stk.pop();
         double result = op1 * op2;
         stk.push(result);
         return result;
      }//end multiply
   	/**Method for error checking user input. If parseInt fails, this method is invoked, and determines whether input is invalid,
   	or an operator.*/
       public static boolean isOperator(String str)
      {
         boolean tf;
         if(str.equals("+") || str.equals("-") || str.equals("/") || str.equals("*"))
            tf = true;
         else if(str.equals("q") || str.equals("Q"))
            tf = false;
         else
         {	
            tf = false;
            System.out.println("Invalid input. Please try again.");
         }
         return tf;
      }//end isOperator
      /**Methods for filling stacks and evaluating expressions.*/
       private static void fillStacks(Stack<Double> stkd, Stack<String> stks,String[] str)
      {
         boolean isOp;
      	
         for(int i = 0; i < str.length; i++)
         {
            try
            {
               stkd.push(Double.parseDouble(str[i]));
            }//end try
                catch (NumberFormatException e)
               {
                  isOp = isOperator(str[i]);
                  if(isOp == true)
                     stks.push(str[i]);
               }//end catch
         }//end for
      }//end fillStacks
      
   	/**perform calculations based on operators, loop until operator stack is empty*/
       private static double calculate(Stack<Double> stkd, Stack<String> stks)
      {
         double result = 0;
         String str = "";
      	
         while(!stks.empty())  
         {
            str = stks.pop();
            if(str.equals("+"))
               result = add(stkd);
            else if(str.equals("-"))
               result = subtract(stkd);
            else if(str.equals("/"))
               result = divide(stkd);
            else if(str.equals("*"))
               result = multiply(stkd);
         }//end while
         return result;
      }
   }//end rpnCalc



and please don't try reporting this because I am not asking anyone to write the full code for me, just tell me what i should do. thank you.

Is This A Good Question/Topic? 0
  • +

Replies To: Question about combining two programs, Java Calulator using Stacks.

#2 ipushmycar  Icon User is offline

  • D.I.C Regular

Reputation: 86
  • View blog
  • Posts: 390
  • Joined: 29-August 10

Re: Question about combining two programs, Java Calulator using Stacks.

Posted 29 November 2012 - 01:26 PM

Instead of reading in the input from the user take the input from the GUI. Probably the display box. Parse the input, push and pop operands to a stack and operators to another. I believe with prefix you can use one stack if you start from the end of the input.
Was This Post Helpful? 0
  • +
  • -

#3 mbilal1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 20-September 12

Re: Question about combining two programs, Java Calulator using Stacks.

Posted 29 November 2012 - 01:56 PM

View Postipushmycar, on 29 November 2012 - 01:26 PM, said:

Instead of reading in the input from the user take the input from the GUI. Probably the display box. Parse the input, push and pop operands to a stack and operators to another. I believe with prefix you can use one stack if you start from the end of the input.


That actually helped a lot and helped make me think of a way to do it. I just essentially merged the two codes into one. Here is the what I have so far. The only problem that I have right now is that I do not know how to make my "equal" sign work.

import java.awt.*;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.*;
import java.util.*;
public class Calculator extends JFrame implements ActionListener {
	


	public static void main(String args[])
     {
		  
            Calculator cal=new Calculator("Calc");
     }
	 
	String numbers[]={"0","1","2","3","4","5","6","7","8","9","+","-","*","/",".","CE","C","=","+/-"};
    JButton button[]=new JButton[19];
    Panel p[]=new Panel[6];
    TextField text;
    Box box;
    FlowLayout fv;
     public  Calculator(String string)
    {
       
           this.setDefaultCloseOperation(EXIT_ON_CLOSE);
           box=Box.createVerticalBox();
           fv=new FlowLayout();
           fv.setVgap(20);

         this.setLocationRelativeTo(null);       
           for(int i=0;i<numbers.length;i++)
           {
                  button[i]=new JButton(numbers[i]);
                  button[i].addActionListener(this);
                  if(i!=15&&i!=16)
                  {
                         button[i].setPreferredSize(new Dimension(55,35));
                  }
                  else
                  {
                           button[i].setPreferredSize(new Dimension(85,35));
                  }
                  if(i<6)
                  {
                         p[i]=new Panel();
                         box.add(p[i]);
                  }
                  if(i==0)
                  {
                         text=new TextField("0",30);
                         p[0].add(text);
                  }
           }
           p[1].add(button[7]);p[1].add(button[8]);p[1].add(button[9]);p[1].add(button[10]); //7,8,9,+
           p[2].add(button[4]);p[2].add(button[5]);p[2].add(button[6]);p[2].add(button[11]); //4,5,6,-
           p[3].add(button[1]);p[3].add(button[2]);p[3].add(button[3]);p[3].add(button[12]); //1,2,3, *
           p[4].add(button[0]);p[4].add(button[14]);p[4].add(button[18]);p[4].add(button[13]); //0,., +/-, /
           p[5].add(button[15]);p[5].add(button[16]);p[5].add(button[17]); //CE, C, =
           this.add(box);
           this.setBounds(520,200,280,320);
           this.setResizable(false);
           this.setVisible(true);
           this.validate();
    }
       int press=0;                            
       int press1=0;                          
       int press2=0;                           
       int strlen=0;                           
       StringBuffer str=new StringBuffer("0"); 
       StringBuffer str2=new StringBuffer("0"); 
       double sum1=0;                          
	
	 public void actionPerformed(ActionEvent e){
		 
		 //display numbers
		 if(e.getSource()==button[0])
	        {
	               this.displayNumber(0);
	        }
	        if(e.getSource()==button[1])
	        {
	               this.displayNumber(1);
	        }
	        if(e.getSource()==button[2])
	        {
	               this.displayNumber(2);
	        }
	        if(e.getSource()==button[3])
	        {
	               this.displayNumber(3);
	        }
	        if(e.getSource()==button[4])
	        {
	               this.displayNumber(4);
	        }
	        if(e.getSource()==button[5])
	        {
	               this.displayNumber(5);
	        }
	        if(e.getSource()==button[6])
	        {
	               this.displayNumber(6);
	        }
	        if(e.getSource()==button[7])
	        {
	               this.displayNumber(7);
	        }
	        if(e.getSource()==button[8])
	        {
	               this.displayNumber(8);
	        }
	        if(e.getSource()==button[9])
	        {
	         this.displayNumber(9);
	        }
	        
	        //other variables
	        if(e.getSource()==button[10])             
	        {
	            this.pressOperator(10);
	        }
	     if(e.getSource()==button[11])             
	        {
	            this.pressOperator(11);
	        }
	        if(e.getSource()==button[12])             
	     {
	               this.pressOperator(12);
	        }
	        if(e.getSource()==button[13])             
	        {
	        this.pressOperator(13);
	        }   
	        if(e.getSource()==button[14])             
	        {
	               if(str.charAt(str.length()-1)!='+'&&str.charAt(str.length()-1)!='-'&&str.charAt(str.length()-1)!='*'&&str.charAt(str.length()-1)!='/'&&press!=1)
	               {
	                      str.append(button[14].getText());
	                      str2.append(button[14].getText());
	                      text.setText(str.toString());
	                      press=1;
	               }
	        }
	        if(e.getSource()==button[18])             
	        {
	               if(str.charAt(str.length()-1)!='+'&&str.charAt(str.length()-1)!='-'&&str.charAt(str.length()-1)!='*'&&str.charAt(str.length()-1)!='/')
	               {
	                      if(press2==0)
	                      {
	                             str.insert(strlen, "-");
	                             str2.insert(strlen, "@");               
	                             text.setText(str.toString());
	                             press2=1;
	                      }
	                      else
	                      {
	                             str.deleteCharAt(strlen);
	                             str2.deleteCharAt(strlen);
	                             text.setText(str.toString());
	                             press2=0;
	                      }
	               }
	        }
	        if(e.getSource()==button[15])             
	        {
	               if(strlen!=0)
	               {
	                 str.delete(strlen, str.length());
	                 str2.delete(strlen, str2.length());
	                 text.setText(str.toString());
	               }
	               else
	               {
	                      str.delete(0,str.length());
	                      str2.delete(0,str2.length());
	                      str.append("0");
	                      str2.append("0");
	                      text.setText(str.toString());
	                      press=0;
	                      press2=0;
	               }
	        }
	        if(e.getSource()==button[16])            
	     {
	             str.delete(0, str.length());
	             str2.delete(0, str2.length());
	              str.append("0");
	              str2.append("0");
	              text.setText(str.toString());
	              press=0;
	              press1=0;
	              press2=0;
	              strlen=0;
	        }
	        if(e.getSource()==button[17])             
	        {
	        	 
	        }
	      
	 }
	 
	  public void pressOperator(int i)          
      {
              if(str.charAt(str.length()-1)!='+'&&str.charAt(str.length()-1)!='-'&&str.charAt(str.length()-1)!='*'&&str.charAt(str.length()-1)!='/'&&str.charAt(str.length()-1)!='.')    
              {
                     str.append(button[i].getText());
                     str2.append(button[i].getText());
                     text.setText(str.toString());
                     press=0;
                     press1=1;
                     press2=0;
                     strlen=str.length();
              }
      }
	    public void displayNumber(int i)         ///number display to box   
	    {
	          if(press1!=1&&press!=1&&str.charAt(0)=='0')
	               {
	                      str.replace(0, 1,button[i].getText());
	                      str2.replace(0, 1,button[i].getText());
	                   text.setText(str.toString());
	               }
	               else
	               {
	                      str.append(button[i].getText());
	                      str2.append(button[i].getText());
	                      text.setText(str.toString());
	               }   
	    }
	 private static double add(Stack<Double> stk)
     {
        double op2 = stk.pop();
        double op1 = stk.pop();
        double result = op1 + op2;
        stk.push(result);
        return result;
     }// end add
     
      private static double subtract(Stack<Double> stk)
     {
        double op2 = stk.pop();
        double op1 = stk.pop();
        double result = op1 - op2;
        stk.push(result);
        return result;
     }// end subtract
     
      private static double divide(Stack<Double> stk)
     {
        double op2 = stk.pop();
        double op1 = stk.pop();
        double result = op1 / op2;
        stk.push(result);
        return result;
     }//end divide
  	
      private static double multiply(Stack<Double> stk)
     {
        double op2 = stk.pop();
        double op1 = stk.pop();
        double result = op1 * op2;
        stk.push(result);
        return result;
     }//end multiply
      
  	/**perform calculations based on operators, loop until operator stack is empty*/
      private static double calculate(Stack<Double> stkd, Stack<String> stks)
     {
        double result = 0;
        String str = "";
     	
        while(!stks.empty())  
        {
           str = stks.pop();
           if(str.equals("+"))
              result = add(stkd);
           else if(str.equals("-"))
              result = subtract(stkd);
           else if(str.equals("/"))
              result = divide(stkd);
           else if(str.equals("*"))
              result = multiply(stkd);
        }//end while
        return result;
     }
	
	
}




the equal operation is at line 201.
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: Question about combining two programs, Java Calulator using Stacks.

Posted 29 November 2012 - 04:53 PM

You are writing a console or a GUI application ?
Use one or the other but do not mix them... no Scanner if you have a GUI. Switching from one to the other will make any user become sick
Was This Post Helpful? 0
  • +
  • -

#5 mbilal1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 20-September 12

Re: Question about combining two programs, Java Calulator using Stacks.

Posted 01 December 2012 - 02:32 PM

Well i am writing a GUI application, and i was trying to turn the console i found and put it into a GUI.
Look at my second code, it doesnt have a scanner. The only problem i have with that is the what does the equal button do when pressed.

View Postpbl, on 29 November 2012 - 04:53 PM, said:

You are writing a console or a GUI application ?
Use one or the other but do not mix them... no Scanner if you have a GUI. Switching from one to the other will make any user become sick

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1