Hey everybody! So my problem is the very last part, getting the results of my calculation. So what i've done is created a stack with my very own stack class. The = button is suppose to display the result but i get a runtime error. Please help me out. Oh i also created an array of chars. I used those chars and placed it into a method so that way i can get the results.

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

/**
 *
 * @author Giovanni M
 */
public class JCalculator implements ActionListener {
    JFrame jfrm;
    JFrame jfrm2;
    JTextField txt;
    JLabel results;
    String str= "";
    Stack operands = new Stack();
    
    
    
    JCalculator(){
        jfrm = new JFrame("JCalc");
        jfrm.getContentPane().setLayout(new GridLayout(0,1));
        jfrm.setSize(210,210);
        
       results = new JLabel("",SwingConstants.RIGHT);
       jfrm.getContentPane().add(results);
       jfrm.setLocation(400,300);
       jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
       JButton[] calbut= new JButton[14];
       String []but = {"7","8","9","/","4","5","6","*","1","2","3","-","0","C"
       };
       JButton equal = new JButton("=");
       JButton add = new JButton("+");
      
       JPanel jbutton = new JPanel();
       jbutton.setLayout(new GridLayout(4,3));
       for(int i=0; i< but.length;i++){
           jbutton.add(calbut[i] = new JButton(but[i]));
           //jfrm.getContentPane().add(calbut[i]);
           calbut[i].addActionListener(this);
       }
       jbutton.add(equal);
       jbutton.add(add);
       
       equal.addActionListener(this);
       add.addActionListener(this);
       
       jfrm.getContentPane().add(jbutton);
       /*JMenu j = new JMenu ("C",KeyEvent.VK_C);
        j.setAccelerator(
         KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));*/
               
        jfrm.setVisible(true);
    }
    public void actionPerformed(ActionEvent ae){
        char[] a = new char[0];
        int used = 0;
        if(used == a.length){
            char[] newa= new char[a.length + 1];
            for(int i = 0; i <used; i++) newa[i]= a[i];
            a= newa;
        }
        
        if(ae.getActionCommand().equals("1")){
            str = results.getText();
            results.setText(str + "1");
        }
        if(ae.getActionCommand().equals("2")){
            str = results.getText();
            results.setText(str + "2");
        }
        if(ae.getActionCommand().equals("3")){
            str = results.getText();
            results.setText(str + "3");
        }
        if(ae.getActionCommand().equals("4")){
            str = results.getText();
            results.setText(str + "4");
        }
        if(ae.getActionCommand().equals("5")){
            str = results.getText();
            results.setText(str + "5");
        }
        if(ae.getActionCommand().equals("6")){
            str = results.getText();
            results.setText(str + "6");
        }
        if(ae.getActionCommand().equals("7")){
            str = results.getText();
            results.setText(str + "7");
        }
        if(ae.getActionCommand().equals("8")){
            str = results.getText();
            results.setText(str + "8");
        }
        if(ae.getActionCommand().equals("9")){
            str = results.getText();
            results.setText(str + "9");
        }
        if(ae.getActionCommand().equals("0")){
            str = results.getText();
            results.setText(str + "0");
            //operands.push(0);
        }
        if(ae.getActionCommand().equals("+")){
            str = results.getText();
            double operand = Double.parseDouble(str);
            operands.push(operand);
            results.setText("");
            a[used]= '+';
            used++;
            
        }
        if(ae.getActionCommand().equals("-")){
            str = results.getText();
            double operand = Double.parseDouble(str);
            operands.push(operand);
            results.setText("");
            a[used]= '+';
            used++;
        }
        if(ae.getActionCommand().equals("/")){
            str = results.getText();
            double operand = Double.parseDouble(str);
            operands.push(operand);
            results.setText("");
            a[used]= '+';
            used++;
        }
        if(ae.getActionCommand().equals("*")){
            str = results.getText();
            double operand = Double.parseDouble(str);
            operands.push(operand);
            results.setText("");
            a[used]= '*';
            used++;
        }
        if(ae.getActionCommand().equals("=")){
            
            for(int i = 0; i< used; i++){
               performBinaryOp(a[i]);
            }
            str = (String) operands.pop();
            results.setText(str);
        }

        
        
    }
     public void performBinaryOp(char nextOperation) {

        double leftOperand, rightOperand;
        Double result = new Double(0);

        rightOperand = (double) operands.pop();
        leftOperand = (double)operands.pop();

        switch (nextOperation) {
            case '+':
                result = new Double(leftOperand + rightOperand);
                break;
            case '-':
                result = new Double(leftOperand - rightOperand);
                break;
            case '*':
                result = new Double(leftOperand * rightOperand);
                break;
            case '/':
                result = new Double(leftOperand / rightOperand);
                break;
        }
        operands.push(result);
    }

    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JCalculator();                
            }            
        });        
    }
}

Hey everybody! So my problem is the very last part, getting the results of my calculation. So what i've done is created a stack with my very own stack class. The = button is suppose to display the result but i get a runtime error. Please help me out. Oh i also created an array of chars. I used those chars and placed it into a method so that way i can get the results.

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

/**
 *
 * @author Giovanni M
 */
public class JCalculator implements ActionListener {
    JFrame jfrm;
    JFrame jfrm2;
    JTextField txt;
    JLabel results;
    String str= "";
    Stack operands = new Stack();
    
    
    
    JCalculator(){
        jfrm = new JFrame("JCalc");
        jfrm.getContentPane().setLayout(new GridLayout(0,1));
        jfrm.setSize(210,210);
        
       results = new JLabel("",SwingConstants.RIGHT);
       jfrm.getContentPane().add(results);
       jfrm.setLocation(400,300);
       jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
       JButton[] calbut= new JButton[14];
       String []but = {"7","8","9","/","4","5","6","*","1","2","3","-","0","C"
       };
       JButton equal = new JButton("=");
       JButton add = new JButton("+");
      
       JPanel jbutton = new JPanel();
       jbutton.setLayout(new GridLayout(4,3));
       for(int i=0; i< but.length;i++){
           jbutton.add(calbut[i] = new JButton(but[i]));
           //jfrm.getContentPane().add(calbut[i]);
           calbut[i].addActionListener(this);
       }
       jbutton.add(equal);
       jbutton.add(add);
       
       equal.addActionListener(this);
       add.addActionListener(this);
       
       jfrm.getContentPane().add(jbutton);
       /*JMenu j = new JMenu ("C",KeyEvent.VK_C);
        j.setAccelerator(
         KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));*/
               
        jfrm.setVisible(true);
    }
    public void actionPerformed(ActionEvent ae){
        char[] a = new char[0];
        int used = 0;
        if(used == a.length){
            char[] newa= new char[a.length + 1];
            for(int i = 0; i <used; i++) newa[i]= a[i];
            a= newa;
        }
        
        if(ae.getActionCommand().equals("1")){
            str = results.getText();
            results.setText(str + "1");
        }
        if(ae.getActionCommand().equals("2")){
            str = results.getText();
            results.setText(str + "2");
        }
        if(ae.getActionCommand().equals("3")){
            str = results.getText();
            results.setText(str + "3");
        }
        if(ae.getActionCommand().equals("4")){
            str = results.getText();
            results.setText(str + "4");
        }
        if(ae.getActionCommand().equals("5")){
            str = results.getText();
            results.setText(str + "5");
        }
        if(ae.getActionCommand().equals("6")){
            str = results.getText();
            results.setText(str + "6");
        }
        if(ae.getActionCommand().equals("7")){
            str = results.getText();
            results.setText(str + "7");
        }
        if(ae.getActionCommand().equals("8")){
            str = results.getText();
            results.setText(str + "8");
        }
        if(ae.getActionCommand().equals("9")){
            str = results.getText();
            results.setText(str + "9");
        }
        if(ae.getActionCommand().equals("0")){
            str = results.getText();
            results.setText(str + "0");
            //operands.push(0);
        }
        if(ae.getActionCommand().equals("+")){
            str = results.getText();
            double operand = Double.parseDouble(str);
            operands.push(operand);
            results.setText("");
            a[used]= '+';
            used++;
            
        }
        if(ae.getActionCommand().equals("-")){
            str = results.getText();
            double operand = Double.parseDouble(str);
            operands.push(operand);
            results.setText("");
            a[used]= '+';
            used++;
        }
        if(ae.getActionCommand().equals("/")){
            str = results.getText();
            double operand = Double.parseDouble(str);
            operands.push(operand);
            results.setText("");
            a[used]= '+';
            used++;
        }
        if(ae.getActionCommand().equals("*")){
            str = results.getText();
            double operand = Double.parseDouble(str);
            operands.push(operand);
            results.setText("");
            a[used]= '*';
            used++;
        }
        if(ae.getActionCommand().equals("=")){
            
            for(int i = 0; i< used; i++){
               performBinaryOp(a[i]);
            }
            str = (String) operands.pop();
            results.setText(str);
        }

        
        
    }
     public void performBinaryOp(char nextOperation) {

        double leftOperand, rightOperand;
        Double result = new Double(0);

        rightOperand = (double) operands.pop();
        leftOperand = (double)operands.pop();

        switch (nextOperation) {
            case '+':
                result = new Double(leftOperand + rightOperand);
                break;
            case '-':
                result = new Double(leftOperand - rightOperand);
                break;
            case '*':
                result = new Double(leftOperand * rightOperand);
                break;
            case '/':
                result = new Double(leftOperand / rightOperand);
                break;
        }
        operands.push(result);
    }

    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JCalculator();                
            }            
        });        
    }
}

well could you elaborate on the error you are getting? expected outcome and the actual outcome of the app

Say i pushed 5 + 6=

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
at jcalculator.JCalculator.actionPerformed(JCalculator.java:151)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

here is my stack class to help understand what i did with it

import java.util.Scanner;
public class Stack {
        double []stack = new double[10];
        int S_Index = 10;

        public void Display_Stack(){
            if (S_Index < 10){
                for(int i = S_Index; i < 10; i++){
                    //stack[i]= stack [i];
                            
                    System.out.println("Stack[" + i + "] = " + stack[i]);
                }
            }
            if (S_Index == 10){
                System.out.println("The stack is empty- Nothing to display");
            }
        }
        public void push(double x){
            if (S_Index == 0){
                System.out.println("Cannot push into stack");
            }
            else{
                //Scanner sc = new Scanner(System.in);
                S_Index--;
                //System.out.println("Stack at: " + S_Index);
                //ystem.out.print("Enter a number into stack: ");
                stack[S_Index]= x;
            }
        }
        public double pop(){
            if (S_Index == 10){
                return 0;
                //System.out.println("Cannot pop the stack.");
            }
            else{
                return stack[S_Index++];
                
            }
        }

Say i pushed 5 + 6=

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
at jcalculator.JCalculator.actionPerformed(JCalculator.java:151)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

That error is because you are trying to explicitly cast a double to a string, try this:

str = String.valueOf(operands.pop());

but besides that problem there is another when i press say 3+5= it gives me the first amount i entered as the answer i.e 3

I think this is happening because your used integer is never being increased? Hmm i put a println in you event for the '=' button and it keeps saying that used is 0, so your preformbinaryop() method never executes, i think the reason is because you keep redeclaring the int used in the actionperformed method and your char[] a! also your actionperformed methods for the numbers should have operands.push(THENUMBER) where the number is 0-9 depending or else you wont be saving them to the stack

Edited 4 Years Ago by DavidKroukamp: n/a

hmm you're right! any suggestions

Suggestions: declare the integer 'used', and char array 'a' as Global variables i.e:

public class JCalculator implements ActionListener {

    JFrame jfrm;
    JFrame jfrm2;
    JTextField txt;
    JLabel results;
    String str = "";
    Stack operands = new Stack();

    char[] a = new char[0];
    int used = 0;

Next change that str=(String)... to:

str = String.valueOf(operands.pop());

and finally push all the numbers in their respective actionPerformed() methods ie:

if (ae.getActionCommand().equals("0")) {
            str = results.getText();
            results.setText(str + "0");
            operands.push(0);
        }

and take away your:

import java.util.Stack;

it will conflict with your own stack and cause problems

Edited 4 Years Ago by DavidKroukamp: n/a

This question has already been answered. Start a new discussion instead.