Simple Calculator in JAVA
This is a simple java calculator project to calculate basic arithmetic operations using GUI features of Java extending JFrame Class. The source code is organized in two files. They are:1. Main.java and
2. Calc_Frame.java
Before actually digging deeper into the source code, lets first see the the output of the project tested with an input expression 9/2*3 whose obvious output after calculation is 13.5
Here are the snapshots:
Figure: Input of test expression 9/2*3
Figure: Result of test input expression.
1. Main.java
//Contents of the file "Main.java"/**
* Created by Bikal Adhikari on 12/18/2014.
*/
public class Main {
public static void main(String[] args) {
Calc_Frame m=new Calc_Frame("BKL-Calculator");
}
}
2. Calc_Frame.java
//Contents of the file "Calc_Frame.java"/**
* Created by Bikal Adhikari on 12/18/2014.
*/
import java.awt.Container;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calc_Frame extends JFrame {
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
/*Text Field For emulating Calculator Screen*/
JTextArea CalcScreen = new JTextArea();
/*Defining Buttons For keys of Calculator*/
JButton b0 = new JButton("7");
JButton b1 = new JButton("8");
JButton b2 = new JButton("9");
JButton b3 = new JButton("/");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("*");
JButton b8 = new JButton("1");
JButton b9 = new JButton("2");
JButton b10 = new JButton("3");
JButton b11 = new JButton("-");
JButton b12 = new JButton("0");
JButton b13 = new JButton(".");
JButton b14 = new JButton("=");
JButton b15 = new JButton("+");
public Calc_Frame(String str) {
super(str);
Container c = getContentPane();
p1.setLayout(new GridLayout(1, 1, 10, 450));
p2.setLayout(new GridLayout(4, 4));
p1.add(CalcScreen);
CalcScreen.setEditable(false);
/*Adding Buttons to panel p2*/
p2.add(b0);
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.add(b7);
p2.add(b8);
p2.add(b9);
p2.add(b8);
p2.add(b9);
p2.add(b10);
p2.add(b11);
p2.add(b12);
p2.add(b13);
p2.add(b14);
p2.add(b15);
/*Adding panels to container */
c.add(p1);
c.add(p2, BorderLayout.SOUTH);
/*Setting Size of the Frame*/
setSize(250, 200);
setVisible(true);
/*Handler for Button Event Handling*/
Handler h = new Handler();
/*Registering Handler into Action Listener*/
b0.addActionListener(h);
b1.addActionListener(h);
b2.addActionListener(h);
b3.addActionListener(h);
b4.addActionListener(h);
b5.addActionListener(h);
b6.addActionListener(h);
b7.addActionListener(h);
b8.addActionListener(h);
b9.addActionListener(h);
b10.addActionListener(h);
b11.addActionListener(h);
b12.addActionListener(h);
b13.addActionListener(h);
b14.addActionListener(h);
b15.addActionListener(h);
}
/*Class to handle event generated by the button press*/
class Handler implements ActionListener {
int pos=0;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b0) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("7",pos);
}
if (e.getSource() == b1) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("8",pos);
}
if (e.getSource() == b2) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("9",pos);
}
if (e.getSource() == b3) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("/",pos);
}
if (e.getSource() == b4) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("4",pos);
}
if (e.getSource() == b5) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("5",pos);
}
if (e.getSource() == b6) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("6",pos);
}
if (e.getSource() == b7) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("*",pos);
}
if (e.getSource() == b8) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("1",pos);
}
if (e.getSource() == b9) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("2",pos);
}
if (e.getSource() == b10) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("3",pos);
}
if (e.getSource() == b11) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("-",pos);
}
if (e.getSource() == b12) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("0",pos);
}
if (e.getSource() == b13) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert(".",pos);
}
//Equals to Button
if (e.getSource() == b14) {
String str=CalcScreen.getText();
double a=eval(str);
CalcScreen.setText(null);
String abc = Double.toString(a);
CalcScreen.insert(abc,0);
}
if (e.getSource() == b15) {
pos = CalcScreen.getCaretPosition(); //get the cursor position
CalcScreen.insert("+",pos);
}
}
}//Class Handler Ends Here
/**
* This Function performs job of parsing arithmetic expressions given to the calculator
* It basically supports parsing expression containing Division, Multiplication, Addition and Subtraction
* */
public static double eval(final String str) {
class Parser {//Nested Class
int pos = -1, c;
void eatChar() {
c = (++pos < str.length()) ? str.charAt(pos) : -1;
}
void eatSpace() {
while (Character.isWhitespace(c)) eatChar();
}
double parse() {
eatChar();
double v = parseExpression();
if (c != -1) throw new RuntimeException("Unexpected: " + (char)c);
return v;
}
// Grammar:
// expression = term | expression `+` term | expression `-` term
// term = factor | term `*` factor | term `/` factor | term brackets
// factor = brackets | number | factor `^` factor
// brackets = `(` expression `)`
double parseExpression() {
double v = parseTerm();
for (;;) {
eatSpace();
if (c == '+') { // addition
eatChar();
v += parseTerm();
} else if (c == '-') { // subtraction
eatChar();
v -= parseTerm();
} else {
return v;
}
}
}
double parseTerm() {
double v = parseFactor();
for (;;) {
eatSpace();
if (c == '/') { // division
eatChar();
v /= parseFactor();
} else if (c == '*' || c == '(') { // multiplication
if (c == '*') eatChar();
v *= parseFactor();
} else {
return v;
}
}
}
double parseFactor() {
double v;
boolean negate = false;
eatSpace();
if (c == '(') { // brackets
eatChar();
v = parseExpression();
if (c == ')') eatChar();
} else { // numbers
if (c == '+' || c == '-') { // unary plus & minus
negate = c == '-';
eatChar();
eatSpace();
}
StringBuilder sb = new StringBuilder();
while ((c >= '0' && c <= '9') || c == '.') {
sb.append((char)c);
eatChar();
}
if (sb.length() == 0) throw new RuntimeException("Unexpected: " + (char)c);
v = Double.parseDouble(sb.toString());
}
eatSpace();
if (c == '^') { // exponentiation
eatChar();
v = Math.pow(v, parseFactor());
}
if (negate) v = -v; // exponentiation has higher priority than unary minus: -3^2=-9
return v;
}
}
return new Parser().parse();
}
}//Class Calc_Frame ends here
All the necessary project files are included in this zipped archive. To download click here.
Nice Program and Article for Java Programmers. Become a Digital Marketing Professional and earn huge money
ReplyDeleteThanks for this amazing article on Simple Calculator in JAVA I was Just searching for Oven repair and found this amazing website of yours.
ReplyDeleteBookMyEssay offers a powerful factoring expressions calculator, simplifying complex algebraic equations swiftly. Its user-friendly interface and advanced algorithms provide accurate results for polynomial factoring, aiding students and professionals alike. A reliable tool for enhancing mathematical problem-solving skills, available at your fingertips.
ReplyDeleteYou can create a simple fluentbit calculator in one line in Java using a ternary operator and basic arithmetic operations.
ReplyDelete