Write a Java program to create a simple calculator using Grid Layout with digits and +, -, *, % operators, a text field, and handle divide-by-zero exception.
Experiment 2: Write a Java program to create a simple calculator using Grid Layout with digits and +, -, *, % operators, a text field, and handle divide-by-zero exception.
Aim
Write a Java program to create a simple calculator using Grid Layout with digits and +, -, *, % operators, a text field, and handle divide-by-zero exception.
Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
JTextField display;
JButton[] numberButtons = new JButton[10];
JButton addButton;
JButton subButton;
JButton mulButton;
JButton modButton;
JButton equalButton;
JButton clearButton;
double firstNumber = 0;
double secondNumber = 0;
char operator;
Calculator() {
setTitle("Simple Calculator");
setSize(350, 450);
setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE
);
setLayout(new BorderLayout(10, 10));
/*
* Display field
*/
display = new JTextField();
display.setFont(
new Font("Arial", Font.BOLD, 24)
);
display.setHorizontalAlignment(
JTextField.RIGHT
);
display.setEditable(false);
add(
display,
BorderLayout.NORTH
);
/*
* Calculator buttons
*/
JPanel panel =
new JPanel();
panel.setLayout(
new GridLayout(
4,
4,
5,
5
)
);
/*
* Number buttons
*/
for (
int i = 0;
i <= 9;
i++
) {
numberButtons[i] =
new JButton(
String.valueOf(i)
);
numberButtons[i].setFont(
new Font(
"Arial",
Font.BOLD,
18
)
);
numberButtons[i].addActionListener(
this
);
}
/*
* Operator buttons
*/
addButton =
new JButton("+");
subButton =
new JButton("-");
mulButton =
new JButton("*");
modButton =
new JButton("%");
equalButton =
new JButton("=");
clearButton =
new JButton("C");
/*
* Add action listeners
*/
addButton.addActionListener(this);
subButton.addActionListener(this);
mulButton.addActionListener(this);
modButton.addActionListener(this);
equalButton.addActionListener(this);
clearButton.addActionListener(this);
/*
* Add buttons to GridLayout
*/
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
panel.add(numberButtons[9]);
panel.add(addButton);
panel.add(numberButtons[4]);
panel.add(numberButtons[5]);
panel.add(numberButtons[6]);
panel.add(subButton);
panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(mulButton);
panel.add(numberButtons[0]);
panel.add(modButton);
panel.add(equalButton);
panel.add(clearButton);
add(
panel,
BorderLayout.CENTER
);
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void actionPerformed(
ActionEvent e
) {
String command =
e.getActionCommand();
/*
* Number button
*/
if (
command.matches(
"[0-9]"
)
) {
display.setText(
display.getText()
+ command
);
return;
}
/*
* Clear button
*/
if (
command.equals("C")
) {
display.setText("");
firstNumber = 0;
secondNumber = 0;
return;
}
/*
* Operator button
*/
if (
command.equals("+")
||
command.equals("-")
||
command.equals("*")
||
command.equals("%")
) {
if (
display.getText().isEmpty()
) {
return;
}
firstNumber =
Double.parseDouble(
display.getText()
);
operator =
command.charAt(0);
display.setText("");
return;
}
/*
* Equal button
*/
if (
command.equals("=")
) {
if (
display.getText().isEmpty()
) {
return;
}
secondNumber =
Double.parseDouble(
display.getText()
);
double result = 0;
try {
switch (operator) {
case '+':
result =
firstNumber
+ secondNumber;
break;
case '-':
result =
firstNumber
- secondNumber;
break;
case '*':
result =
firstNumber
* secondNumber;
break;
case '%':
if (
secondNumber == 0
) {
throw new ArithmeticException(
"Cannot perform modulo by zero."
);
}
result =
firstNumber
% secondNumber;
break;
default:
display.setText(
"Invalid Operation"
);
return;
}
display.setText(
String.valueOf(result)
);
}
catch (
ArithmeticException ex
) {
JOptionPane.showMessageDialog(
this,
ex.getMessage(),
"Arithmetic Error",
JOptionPane.ERROR_MESSAGE
);
display.setText("");
}
}
}
public static void main(
String[] args
) {
SwingUtilities.invokeLater(
() -> new Calculator()
);
}
}
Output
A calculator window is displayed with a text field and buttons arranged using Grid Layout.
The calculator performs addition, subtraction, multiplication and modulo operations.
If modulo by zero is attempted, an appropriate arithmetic error message is displayed.
Sample Operations
10 + 20 = 30.0 20 - 5 = 15.0 6 * 5 = 30.0 17 % 5 = 2.0 10 % 0 Arithmetic Error: Cannot perform modulo by zero.
Result
Thus, a Java program to create a simple calculator using Grid Layout with digits and +, -, *, % operators and handling divide-by-zero/modulo-by-zero exception was successfully executed.
💻 Run This Java Program
Write a Java program to create a simple calculator using Grid Layout with digits and +, -, *, % operators, a text field, and handle divide-by-zero exception.
The selected Java program is loaded
automatically into the editor.
Edit the program, provide input if required
and click Run.