0% found this document useful (0 votes)
107 views11 pages

Calculator

This code defines a Java calculator applet with the following functionality: - It contains buttons for numbers 0-9, basic math operators, parentheses, clear, and equals. - Clicking buttons appends that digit/operator to the display or clears the display. - The equals button evaluates the expression and displays the result. - Methods are included to initialize the applet, handle button clicks and events, clear the display, and evaluate expressions.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views11 pages

Calculator

This code defines a Java calculator applet with the following functionality: - It contains buttons for numbers 0-9, basic math operators, parentheses, clear, and equals. - Clicking buttons appends that digit/operator to the display or clears the display. - The equals button evaluates the expression and displays the result. - Methods are included to initialize the applet, handle button clicks and events, clear the display, and evaluate expressions.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Source Code

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*
<APPLET CODE="Calculator.class" WIDTH=205 HEIGHT=210>
</APPLET>
*/

public class Calculator extends Applet implements ActionListener


{

/**************************
Data Members
***************************/

private TextField Panel; //To accept user input and display result
private Button Button0, //This button to pass 0 to panel
Button1, //This button to pass 1 to panel
Button2, //This button to pass 2 to panel
Button3, //This button to pass 3 to panel
Button4, //This button to pass 4 to panel
Button5, //This button to pass 5 to panel
Button6, //This button to pass 6 to panel
Button7, //This button to pass 7 to panel
Button8, //This button to pass 8 to panel
Button9, //This button to pass 9 to panel
ButtonDiv , //This button operate division
ButtonMul, //This button operate multiplication
ButtonAdd, //This button operate addition
ButtonSub, //This button opearte subtraction
ButtonAss, //This button return result
ButtonOpar, //This button call open parentheses
ButtonCpar, //This button call close parentheses
ButtonPoint, //This button to pass . to panel
ButtonClear; //This button clear panel
private int Flag, //Record the state after calculating
Err_lve; //State the error level

/*************************
Initialize similar like Constructor, that is use for Applet
**************************/

public void init()


{
setBackground(Color.yellow); //Set white backgroud
setLayout(null);
resize(205, 210);

Flag = 0;
Err_lve = 0;

Panel = new TextField();


Panel.setBounds( 20, 20, 165, 25);
add(Panel);
Button0 = new Button("0");
Button0.setBounds (20, 160, 25, 25);
add(Button0);
Button1 = new Button("1");
Button1.setBounds (20, 125, 25, 25);
add(Button1);
Button2 = new Button("2");
Button2.setBounds (55, 125, 25, 25);
add(Button2);
Button3 = new Button("3");
Button3.setBounds (90, 125, 25, 25);
add(Button3);
Button4 = new Button("4");
Button4.setBounds (20, 90, 25, 25);
add(Button4);
Button5 = new Button("5");
Button5.setBounds (55, 90, 25, 25);
add(Button5);
Button6 = new Button("6");
Button6.setBounds (90, 90, 25, 25);
add(Button6);
Button7 = new Button("7");
Button7.setBounds (20, 55, 25, 25);
add(Button7);
Button8 = new Button("8");
Button8.setBounds (55, 55, 25, 25);
add(Button8);
Button9 = new Button("9");
Button9.setBounds (90, 55, 25, 25);
add(Button9);
ButtonDiv = new Button("/");
ButtonDiv.setBounds (160, 90, 25, 25);
add(ButtonDiv);
ButtonMul = new Button("*");
ButtonMul.setBounds (125, 90, 25, 25);
add(ButtonMul);
ButtonAdd = new Button("+");
ButtonAdd.setBounds (125, 55, 25, 25);
add(ButtonAdd);
ButtonSub = new Button("-");
ButtonSub.setBounds (160, 55, 25, 25);
add(ButtonSub);
ButtonAss = new Button("=");
ButtonAss.setBounds (90, 160, 25, 25);
add(ButtonAss);
ButtonOpar = new Button("(");
ButtonOpar.setBounds (125, 125, 25, 25);
add(ButtonOpar);
ButtonCpar = new Button(")");
ButtonCpar.setBounds (160, 125, 25, 25);
add(ButtonCpar);
ButtonPoint = new Button(".");
ButtonPoint.setBounds (55, 160, 25, 25);
add(ButtonPoint);
ButtonClear = new Button("Clear");
ButtonClear.setBounds (125, 160, 60, 25);
add(ButtonClear);

Panel.addActionListener(this);
Button0.addActionListener(this);
Button1.addActionListener(this);
Button2.addActionListener(this);
Button3.addActionListener(this);
Button4.addActionListener(this);
Button5.addActionListener(this);
Button6.addActionListener(this);
Button7.addActionListener(this);
Button8.addActionListener(this);
Button9.addActionListener(this);
ButtonDiv.addActionListener(this);
ButtonMul.addActionListener(this);
ButtonAdd.addActionListener(this);
ButtonSub.addActionListener(this);
ButtonAss.addActionListener(this);
ButtonOpar.addActionListener(this);
ButtonCpar.addActionListener(this);
ButtonPoint.addActionListener(this);
ButtonClear.addActionListener(this);
}

/*
Method: paint
Purpose: Draw the outline of calculator *(this method can auto. draw when develop Applet, but it isn't Applet's method)
Parameters: Graphics
Returns: None
*/

public void paint(Graphics graphic)


{
graphic.setColor(Color.green);
graphic.drawRoundRect(0, 0, 190, 195, 15, 15);
graphic.setColor(Color.black);
graphic.drawRoundRect(1, 1, 191, 196, 15, 15);
graphic.drawRoundRect(2, 2, 192, 197, 15, 15);
graphic.drawRoundRect(3, 3, 193, 198, 15, 15);
graphic.drawRoundRect(4, 4, 194, 199, 15, 15);
graphic.setColor(Color.blue);
graphic.fillRoundRect(5, 5, 195, 200, 15, 15);
graphic.setColor(Color.green);
graphic.drawRoundRect(5, 5, 195, 200, 15, 15);
graphic.setColor(Color.green);
graphic.drawString("Jeff & Ailyn's Calculator", 45, 200);
}

/*
Method: actionPerformed
Purpose: Event-handling
Parameters: Action event
Returns: None
*/

public void actionPerformed(ActionEvent event)


{
if (event.getSource() instanceof Button)
{
Button clickedButton = (Button) event.getSource();
if (clickedButton == ButtonClear)
{
ClearPanel();
Flag = 0;
}
else if (clickedButton == ButtonAss)
{
Err_lve = 0;
Compute();
Flag = 1;
}
else
{
if (Flag == 1)
{
ClearPanel(); //clear panel after calculation
Flag = 0;
}
DisplayEx(clickedButton);
}
}
else
{
Err_lve = 0;
Compute();
Flag = 1;
}
}

/*
Method: ClearPanel
Purpose: Clear Panel TextField objects
Parameters: None
Returns: None
*/

private void ClearPanel()


{
Panel.setText("");
}
/*
Method: DisplayEx
Purpose: Display the whole expression that the user enters
Parameters: clickedButton
Returns: None
*/

private void DisplayEx(Button ClickedButton)


{
String tmpstr;
tmpstr = Panel.getText();
if (ClickedButton == Button0) Panel.setText(tmpstr+"0");
if (ClickedButton == Button1) Panel.setText(tmpstr+"1");
if (ClickedButton == Button2) Panel.setText(tmpstr+"2");
if (ClickedButton == Button3) Panel.setText(tmpstr+"3");
if (ClickedButton == Button4) Panel.setText(tmpstr+"4");
if (ClickedButton == Button5) Panel.setText(tmpstr+"5");
if (ClickedButton == Button6) Panel.setText(tmpstr+"6");
if (ClickedButton == Button7) Panel.setText(tmpstr+"7");
if (ClickedButton == Button8) Panel.setText(tmpstr+"8");
if (ClickedButton == Button9) Panel.setText(tmpstr+"9");
if (ClickedButton == ButtonDiv) Panel.setText(tmpstr+"/");
if (ClickedButton == ButtonMul) Panel.setText(tmpstr+"*");
if (ClickedButton == ButtonAdd)Panel.setText(tmpstr+"+");
if (ClickedButton == ButtonSub) Panel.setText(tmpstr+"-");
if (ClickedButton == ButtonOpar)Panel.setText(tmpstr+"(");
if (ClickedButton == ButtonCpar)Panel.setText(tmpstr+")");
if(ClickedButton == ButtonPoint)Panel.setText(tmpstr+".");
}

/*
Method: Compute
Purpose: Calculate the expression and shown the result, when the user hit return key or "=" button.
Parameters: The whole expression
Returns: None
*/

private void Compute()


{
String Tmpstr, Result="";
char ch;
int i, no_of_char,
no_of_par = 0;

Tmpstr = Panel.getText();
no_of_char = Tmpstr.length();

//Expression brief checking


for (i = 0; i < no_of_char; i++)
{
ch = Tmpstr.charAt(i);
if (ch == ')') no_of_par--;
if (no_of_par < 0) Err_lve = 1;
if (ch == '(') no_of_par++;
if (ch < '(' || ch > '9' || ch == ',') Err_lve = 2;
if (ch == '.' && (i+1 < Tmpstr.length()) )
for ( int j = i+1; (j < Tmpstr.length()) && ((Character.isDigit(Tmpstr.charAt(j))) ||
((Tmpstr.charAt(j))) == '.'); j++ )
if (Tmpstr.charAt(j) == '.') Err_lve = 3;
//If an operand has more than one point return
error
}//End of expression brief checking

if (no_of_par != 0) Err_lve = 1; //If open and close parentheses do not match return error

if (Err_lve != 0) Err_msg(Err_lve); //An error perform to prompt error message


else Result = Calculate(Tmpstr); //No error perform to calculate expression
if (Err_lve != 0) Err_msg(Err_lve); //An error perform to prompt error message
else Panel.setText(Result); //No error show result
}
/*
Method: Calculate
Purpose: Implement the expression
Parameters: Expression
Returns: None
*/

private String Calculate(String expression)


{
String result = expression, f_operand, r_operand;
char cha;
int index, f_index, r_index,
no_of_cha = result.length(),
no_of_pare = 0, pare_match = 0, op_index = 0, cp_index = 0;

if (Err_lve == 0)
{
//Checking Parentheses
for (index = 0; index < no_of_cha; index++)
{
cha = result.charAt(index);

if (cha == '(')
{
if (pare_match == 0) op_index = index;
pare_match ++;
no_of_pare ++;
}

if (cha == ')')
{
pare_match --;
if (pare_match == 0) cp_index = index;
}
}//End of checking Parentheses

if (op_index+1 == cp_index) Err_lve = 3;

//Recursive Calculate, when parentheses existed


if (Err_lve == 0 && no_of_pare > 0)
{
if ((op_index == 0) && (cp_index == (no_of_cha - 1)) && (op_index != cp_index)) result =
Calculate(result.substring(op_index + 1, cp_index));
else if (op_index == 0 && cp_index > 0)
{
if ( (Character.isDigit(result.charAt(cp_index+1))) ) Err_lve = 3;
else
{
result = Calculate(result.substring(op_index + 1, cp_index)) +
result.substring(cp_index + 1);
no_of_pare--;
while(no_of_pare != 0)
{
result = Calculate(result);
no_of_pare--;
}
}
}
else if ((op_index > 0) && (cp_index > 0) && (cp_index != no_of_cha -1))
{
if ( (Character.isDigit(result.charAt(cp_index+1))) ||
(Character.isDigit(result.charAt(op_index-1))) ) Err_lve = 3;
else
{
result = result.substring(0, op_index) +
Calculate(result.substring(op_index +1, cp_index)) + result.substring(cp_index +1);
no_of_pare--;
while(no_of_pare != 0)
{
result = Calculate(result);
no_of_pare--;
}
}
}
else if (cp_index == no_of_cha -1 && op_index > 0)
{
if ( (Character.isDigit(result.charAt(op_index-1))) ) Err_lve = 3;
else
{
result = result.substring(0, op_index) +
Calculate(result.substring(op_index + 1, cp_index));
no_of_pare--;
while(no_of_pare != 0)
{
result = Calculate(result);
no_of_pare--;
}
}
}
}//End of recursive Calculate statement

//Implement algorithm
if (no_of_pare == 0 && Err_lve == 0)
{
if ( (!(Character.isDigit(result.charAt(0))) && (result.charAt(0) != '-')) || !
(Character.isDigit(result.charAt(result.length()-1))) ) Err_lve = 3;

//Implement multiply and divide first


for (index = 0; index < result.length() && (Err_lve == 0); index++)
{
cha = result.charAt(index);

if (cha == '*' || cha == '/')


{
if ( !(Character.isDigit(result.charAt(index-1))) || ( !
(Character.isDigit(result.charAt(index+1))) && (result.charAt(index+1) != '-') ) ) Err_lve = 3;
if (result.charAt(index+1) == '-')
if ( !(Character.isDigit(result.charAt(index+2))) ) Err_lve = 3;
if (Err_lve == 0)
{
f_index = index - 1;

if (f_index > 2)
if ( ((result.charAt(f_index-1)) == '-') &&
((result.charAt(f_index-2)) == 'E') )
f_index = f_index - 2;

while ( (f_index > 0) && ((Character.isDigit(result.charAt(f_index-1))) ||


((result.charAt(f_index-1)) == '.') || ((result.charAt(f_index-1)) == 'E')) )
{
f_index--;
}
if (f_index ==1)
if ((result.charAt(f_index-1)) == '-')
f_index--;
if (f_index > 2)
if ( ((result.charAt(f_index-1)) == '-') && !
(Character.isDigit(result.charAt(f_index-2))) )
f_index--;
f_operand = result.substring(f_index, index);

r_index = index + 1;
while ( (r_index < result.length()-1) &&
((Character.isDigit(result.charAt(r_index+1))) || ((result.charAt(r_index+1)) == '.') || ((result.charAt(r_index+1)) == 'E')) )
{
r_index++;
if (r_index < result.length()-2)
if ( ((result.charAt(r_index)) == 'E') &&
((result.charAt(r_index+1)) == '-') )
r_index++;
}
r_operand = result.substring(index+1, r_index+1);

if ( (f_index != 0) && (r_index != result.length()-1) )


{
if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'N') Err_lve =
4; //If an answer is not a number return error
if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'I') Err_lve = 5;
//If an answer is Infinity return error
result = result.substring(0, f_index) + Algorithm(cha, f_operand,
r_operand) + result.substring(r_index+1);
index = 0;
}
else if ( (f_index == 0) && (r_index == result.length()-1) )
{
if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'N')
Err_lve = 4; //If an answer is not a number return error
if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'I')
Err_lve = 5; //If an answer is Infinity return error

result = Algorithm(cha, f_operand, r_operand);


}
else if (f_index == 0)
{
if (Algorithm(cha, f_operand,
r_operand).charAt(0) == 'N') Err_lve = 4; //If an answer is not a number return error
if (Algorithm(cha, f_operand,
r_operand).charAt(0) == 'I') Err_lve = 5; //If an answer is Infinity return error

result = Algorithm(cha, f_operand, r_operand)


+ result.substring(r_index+1);
index = 0;
}
else if (r_index == result.length()-1)
{
if (Algorithm(cha, f_operand,
r_operand).charAt(0) == 'N') Err_lve = 4; //If an answer is not a number return error
if (Algorithm(cha, f_operand,
r_operand).charAt(0) == 'I') Err_lve = 5; //If an answer is Infinity return error

result = result.substring(0, f_index)


+ Algorithm(cha, f_operand, r_operand);
}
}
}
}//End of implement multiply and divide

//Implement add and subtract


for (index = 0; index < result.length() && (Err_lve == 0); index++)
{
if (index == 0 && result.charAt(index) == '-') index = 1;

if (index > 0)
if ( ((result.charAt(index)) == 'E') && ((result.charAt(index+1)) == '-') )
index = index + 2;

cha = result.charAt(index);

if (cha == '+' || cha == '-')


{
if ( !(Character.isDigit(result.charAt(index-1))) || ( !
(Character.isDigit(result.charAt(index+1))) && (result.charAt(index+1) != '-') ) ) Err_lve = 3;
if (result.charAt(index+1) == '-')
if ( !(Character.isDigit(result.charAt(index+2))) ) Err_lve = 3;
if (Err_lve == 0)
{
f_index = 0;
f_operand = result.substring(f_index, index);

r_index = index + 1;
while ( (r_index < result.length()-1) &&
((Character.isDigit(result.charAt(r_index+1))) || ((result.charAt(r_index+1)) == '.') || ((result.charAt(r_index+1)) == 'E')) )
{
r_index++;
if (r_index < result.length()-2)
if ( ((result.charAt(r_index)) == 'E') &&
((result.charAt(r_index+1)) == '-') )
r_index++;
}
r_operand = result.substring(index+1, r_index+1);
result = Algorithm(cha, f_operand, r_operand) +
result.substring(r_index+1);
index = 0;
}
}
}//End of implement add and subtract

}//End of implement algorithm

}
return result;
}

/*
Method: Algorithm
Purpose: Implement the simple expression
Parameters: Operator, front value and rear value
Returns: None
*/

private String Algorithm(char Operator, String F_operand, String R_operand)


{
Double F, R;
double f, r,
ans = 0;
String res;

F = new Double(F_operand);
R = new Double(R_operand);
f = F.doubleValue();
r = R.doubleValue();

if (Operator == '+') ans = f + r;


if (Operator == '-') ans = f - r;
if (Operator == '*') ans = f * r;
if (Operator == '/') ans = f / r;

res = Double.toString(ans);

return res;
}

/*
Method: Err_msg
Purpose: Prompt error message
Parameters: Error level
Returns: None
*/

private void Err_msg(int Err_lve)


{
switch(Err_lve)
{
case 1:
Panel.setText("Parentheses do not match");
break;
case 2:
Panel.setText("Invalid input");
break;
case 3:
Panel.setText("Invalid expression");
break;
case 4:
Panel.setText("Not a number exist");
break;
case 5:
Panel.setText("Infinity exist");
break;
default:
Panel.setText("Unknow error");
break;
}
}
}
/*... End of Calculator.java ...*/
(Calculator.java)

Submitted by:
Jefferson DC. Esguerra
Reynalyn R. Manapat

BSIT – 2b

Submitted to:
Mr. Michael Dennis Perez

Description
Calculator.java is a simple applet that calculates the arithmetic expression from the
text field and returns the result to the text field. The user can enter the expression by typing
within the text field and/or by clicking the buttons.

Note that the arithmetic expression can have numbers with a decimal point, the nested
parentheses and the four binary arithmetic operators, such as addition (+), subtraction (-),
multiplication (*), and division (/). All the numbers entered can be accepted as
positive/negative floating point numbers.

Output

The applet begins with three import statements. The first imports the Abstract
Window Toolkit (AWT) classes which contains support for a window-based, graphical
interface. Applets interact with the user through the AWT, not through the console-based I/O
classes. Next is the java.awt.event package which is capable of handling events and lastly is
the applet package which contains the class Applet. Every applet that you create must be a
subclass of Applet.

The next line is an HTML text file that contains the appropriate Applet tag for the
program to execute an applet in the web browser or in an appletviewer. The program declares
the class Calculator. This class must be declared as public because it will be accessed by
outside code.
Inside class Calculator is the declaration of variables used in the applet and after
that is the initialization of similar like Constructor, which is use for Applet. It sets its
background and layout and the bounds of the buttons used in the application in the applet
environment. It contains addActionListener that registers events each time there was a button
that is pressed or clicked.

public void paint(Graphics graphic) contains the graphics, colors and draw the
outline of the calculator. When the button is clicked, a call is made to the actionPerformed()
method defined in the class of the listener object. An ActionEvent object is passed as a
parameter to it actionPerformed ( ). There is also a method to clear the panel after performing
any operation when you want to enter another expression. The command will output a “ “ that
indicates that there is no value in the text field.

The next method is the DisplayEx ( ) method. Its purpose is to display the whole
expression that the user enters. After it is the Compute ( ) method that calculate the
expressions and show the result when the user hit the return key or the equal (=) button. Next
is the implementation of the expression. The last part of the program is when there was an
invalid entry in the text field, an error message will prompt. For example, if you enter an
invalid expression in the text field, “Invalid expression” will appear on the panel.

You might also like