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

public class JCalculator implements ActionListener {

private JButton[] buttons;
private JLabel display;

//Put button shapes in an array
private String[] button_Shapes = {"7", "8", "9", "/", "4", "5", "6", "x", "1",
                     "2", "3", "-", "0", "C", "=", "+"};

private int operand1, operand2, result;
private String operator;

//Create new form Calculator
public JCalculator(){

    //Create new JFrame container
    JFrame jfrm = new JFrame("Calculator");

    //Set the initial size for frame
    jfrm.setSize(500,500);

    //Terminate the program when the user closes the application.
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set the calculator to center on the screen
    jfrm.setLocationRelativeTo(null);

    //Set the icon
    ImageIcon icon = new ImageIcon("C:/Users/zetsu/Desktop/JCalculator.png");
    jfrm.setIconImage(icon.getImage());

    //Create label
    display = new JLabel("0", JLabel.RIGHT); 

    //Put border around display label
    display.setBorder(BorderFactory.createLineBorder(Color.black));

    //Create a grid layout
    GridLayout layout = new GridLayout(4,4);

    //Create a panel and set layout
    JPanel bottom_Panel = new JPanel();
    bottom_Panel.setLayout(layout);

    //Create an array of buttons
    buttons = new JButton[16];        

    for(int i = 0; i < button_Shapes.length; i++){
        //make new button name
        JButton btn = new JButton("" + button_Shapes[i]);
        buttons[i] = btn;
        //add action listener for each button
        btn.addActionListener(this);
        //add each button to panel
        bottom_Panel.add(btn);
    }

    //Set [=] button to default
    jfrm.getRootPane().setDefaultButton(buttons[14]);

    //Set Mnemonic to Alt+[C]
    buttons[13].setMnemonic(KeyEvent.VK_C);

    //Add label to content pane
    jfrm.add(display, BorderLayout.NORTH);

    //Add panel to content pane
    jfrm.add(bottom_Panel, BorderLayout.CENTER);

    jfrm.setVisible(true);                
}

@Override
public void actionPerformed(ActionEvent e) {
    JButton btn = (JButton)e.getSource();

    if(display.getText().equals("0") 
            || display.getText().equals(button_Shapes[3])
            || display.getText().equals(button_Shapes[7])
            || display.getText().equals(button_Shapes[11])
            || display.getText().equals(button_Shapes[15])){
        display.setText("");
    }

    if(btn == buttons[0] || btn == buttons[1] || btn == buttons[2]
        || btn == buttons[4] || btn == buttons[5] || btn == buttons[6]
        || btn == buttons[8] || btn == buttons[9] || btn == buttons[10]
        || btn == buttons[12]){

        display.setText("" + display.getText()+ btn.getText());

        if(display.getText().length() > 7){
            buttons[0].setEnabled(false);
            buttons[1].setEnabled(false);
            buttons[2].setEnabled(false);
            buttons[4].setEnabled(false);
            buttons[5].setEnabled(false);
            buttons[6].setEnabled(false);
            buttons[8].setEnabled(false);
            buttons[9].setEnabled(false);
            buttons[10].setEnabled(false);
            buttons[12].setEnabled(false);
        }
    }

    if(btn == buttons[3] || btn == buttons[7] || btn == buttons[11]
            || btn == buttons[15]){

        buttons[0].setEnabled(true);
        buttons[1].setEnabled(true);
        buttons[2].setEnabled(true);
        buttons[4].setEnabled(true);
        buttons[5].setEnabled(true);
        buttons[6].setEnabled(true);
        buttons[8].setEnabled(true);
        buttons[9].setEnabled(true);
        buttons[10].setEnabled(true);
        buttons[12].setEnabled(true);

        operand1 = Integer.parseInt(display.getText());
        operator = btn.getText();
        display.setText("" + operator);
    }

    if(btn == buttons[14]){

        buttons[0].setEnabled(true);
        buttons[1].setEnabled(true);
        buttons[2].setEnabled(true);
        buttons[4].setEnabled(true);
        buttons[5].setEnabled(true);
        buttons[6].setEnabled(true);
        buttons[8].setEnabled(true);
        buttons[9].setEnabled(true);
        buttons[10].setEnabled(true);
        buttons[12].setEnabled(true);

        operand2 = Integer.parseInt(display.getText());            
        if(operator.equals(button_Shapes[3])){
            if(operand2 == 0){
                display.setText("Div by 0");
            }
            else{
                result = operand1 / operand2;
            }
        }
        else if(operator.equals(button_Shapes[7])){
            result = operand1 * operand2;
        }
        else if(operator.equals(button_Shapes[11])){
            result = operand1 - operand2;
        }
        else if(operator.equals(button_Shapes[15])){
            result = operand1 + operand2;
        }

        if(String.valueOf(result).length() > 8){
            display.setText("Overflow");
        }
        else{
            display.setText(String.valueOf(result));
        }

    }

    if(btn == buttons[13]){
        buttons[0].setEnabled(true);
        buttons[1].setEnabled(true);
        buttons[2].setEnabled(true);
        buttons[4].setEnabled(true);
        buttons[5].setEnabled(true);
        buttons[6].setEnabled(true);
        buttons[8].setEnabled(true);
        buttons[9].setEnabled(true);
        buttons[10].setEnabled(true);
        buttons[12].setEnabled(true);

        display.setText("0");
    }
}

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

}

I am trying to write a program to create a swing gui of a simple calculator. Initially, the calculator will display a zero. All the operations are in the form: (operand1 operator1 operand2 =) operator2 operand3 = When operand1 is entered, the initial zero disappears and operand1 shows up on the display. When operator1 is pressed, the number on the screen disappears and the operator shows up. When operator2 is entered, the operator disappears and operator2 shows up on screen. When the equal sign is pressed, the result of the operation would be display on the screen. What I am trying to do is display an error "Div by 0" whenever a number divides by zero. However, whenever I divide, add, subtract, or multiply by zero I keep getting the error NumberFormatException. I think the problem is in this if statement:

if(display.getText().equals("0") 
   || display.getText().equals(button_Shapes[3])                    
   || display.getText().equals(button_Shapes[7])                    
   || display.getText().equals(button_Shapes[11])                    
   || display.getText().equals(button_Shapes[15])){            
          display.setText("");
}

The purpose of this if is to erase the zero on the display whenever the first number is pressed or when an operator is pressed. What I think can solve this problem is somehow notify the if statement that operand2 has the value of zero so it doesn't set the text to (""). I don't know how to do that. Please help.

Allen
  • 35
  • 6
  • You should not have a single ActionListener. An ActionListener should perform only one function. When you have multiple if/else clauses in the ActionLIstener you know you have a design problem. So you need to create a separate ActionListener to the "+" button the "-" button etc. You can however share an ActionListener for the "0, 1, 2, 3..." buttons. For an example of this see: https://stackoverflow.com/questions/33739623/how-to-add-a-shortcut-key-for-a-jbutton-in-java/33739732#33739732. Once you do this your code will be easier to debug. – camickr Sep 27 '18 at 20:38
  • You might also want to consider creating a method to change the enabled/disabled status of the button. You pass in a Boolean value (true/false) and just set each button. It saves you having to code the logic multiple time. You may to consider use a loop as well. – camickr Sep 27 '18 at 20:40
  • `However, whenever I divide, add, subtract, or multiply by zero I keep getting the error NumberFormatException` - well you set the text to an empty string and then probably use that empty string in a conversion to an Integer, so that would cause a problem. If the logic was in separate ActionLIsteners it would be more obvious that you don't want to convert 0 to an empty string. Only check for 0, before doing division. – camickr Sep 27 '18 at 20:45

1 Answers1

0

You need to rethink this entire application. But maybe you should try something like this to actually find out if you're dividing by zero:

    try
    {
        //do calculation

    } catch (ArithmeticException ae)
    {
        if (ae.getMessage().equalsIgnoreCase("/ by zero"))
        {
            //do something
        }

    }
trilogy
  • 1,738
  • 15
  • 31