Simple Calculator Program using Java Applet

This is a Java Program to Demonstrate a Basic Calculator using Applet

Problem Description

We have to write a program in Java such that it creates a calculator which allows basic operations of addition, subtraction, multiplication and division.

Expected Input and Output

For creating a calculator, we can have the following different sets of input and output.

```When the addition expression "98+102" is typed,
it is expected that the result is displayed as "98+102=200.0".```

2. To Perform Subtraction :

```When the subtraction expression "200.0-58.75" is typed,
it is expected that the result is displayed as "200.0-58.75=141.25".```

3. To Perform Multiplication :

```When an multiplication expression "141.25*20" is typed,
it is expected that the result is displayed as "141.25*20=2825.0".```

4. To Perform Division : When the denominator is non-zero

```When an division expression "2825.0/5" is typed,
it is expected that the result is displayed as "2825.0/5=565.0".```

5. To Perform Division : When the denominator is zero

Note: Join free Sanfoundry classes at Telegram or Youtube
```When an division expression "565.0/0" is typed,
it is expected that the error is displayed as "565.0/0=Zero Divison Error".```
Problem Solution

1. Create a text field to accept the expression and display the output also.
2. Create buttons for digits and a decimal point.
3. Create a button to clear the complete expression.
4. Create the buttons for operations, that is for addition, subtraction, multiplication and division and an equals button to compute the result.
5. Add ActionListener to all the buttons.
6. Compute the result and display in the text field.

Program/Source Code

Here is source code of the Java Program to create a basic calculator. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.

1. `/*Java Program to Demonstrate a Basic Calculator using Applet*/`
2. `import java.awt.*;`
3. `import java.applet.*;`
4. `import java.awt.event.*;`
5. `public class Calculator extends Applet implements ActionListener`
6. `{`
7. `    TextField inp;`
8. `    //Function to add features to the frame`
9. `    public void init()`
10. `    {`
11. `	setBackground(Color.white);`
12. `	setLayout(null);`
13. `	int i;`
14. `	inp = new TextField();`
15. `	inp.setBounds(150,100,270,50);`
16. `	this.add(inp);`
17. `	Button button[] = new Button[10];`
18. `	for(i=0;i<10;i++)`
19. `	{`
20. `	    button[i] = new Button(String.valueOf(9-i));`
21. `	    button[i].setBounds(150+((i%3)*50),150+((i/3)*50),50,50);`
22. `	    this.add(button[i]);`
23. `	    button[i].addActionListener(this);`
24. `	}`
25. `	Button dec=new Button(".");`
26. `	dec.setBounds(200,300,50,50);`
27. `	this.add(dec);`
28. `	dec.addActionListener(this);`
29. ` `
30. `	Button clr=new Button("C");`
31. `	clr.setBounds(250,300,50,50);`
32. `	this.add(clr);`
33. `	clr.addActionListener(this);`
34. ` `
35. `	Button operator[] = new Button[5];`
36. `	operator[0]=new Button("/");`
37. `	operator[1]=new Button("*");`
38. `	operator[2]=new Button("-");`
39. `	operator[3]=new Button("+");`
40. `	operator[4]=new Button("=");`
41. `	for(i=0;i<4;i++)`
42. `	{`
43. `	    operator[i].setBounds(300,150+(i*50),50,50);`
44. `	    this.add(operator[i]);`
45. `	    operator[i].addActionListener(this);`
46. `	}`
47. `	operator[4].setBounds(350,300,70,50);`
48. `	this.add(operator[4]);`
49. `	operator[4].addActionListener(this);`
50. `    }`
51. `    String num1="";`
52. `    String op="";`
53. `    String num2="";`
54. `    //Function to calculate the expression`
55. `    public void actionPerformed(ActionEvent e)`
56. `    {`
57. `	String button = e.getActionCommand();`
58. `        char ch = button.charAt(0);`
59. `	if(ch>='0' && ch<='9'|| ch=='.') `
60. `	{ `
61. `	    if (!op.equals("")) `
62. `		num2 = num2 + button; `
63. `	    else`
64. `		num1 = num1 + button;   `
65. `	    inp.setText(num1+op+num2); `
66. `	} `
67. `	else if(ch=='C') `
68. `	{ `
69. `	    num1 = op = num2 = ""; `
70. `	    inp.setText(""); `
71. `	}`
72. `	else if (ch =='=') `
73. `	{ `
74. `	    if(!num1.equals("") && !num2.equals(""))`
75. `	    {`
76. `		double temp;`
77. `		double n1=Double.parseDouble(num1);`
78. `		double n2=Double.parseDouble(num2);`
79. `		if(n2==0 && op.equals("/"))`
80. `		{`
81. `		    inp.setText(num1+op+num2+" = Zero Division Error");`
82. `		    num1 = op = num2 = "";`
83. `		}`
84. `		else`
85. `		{`
86. `		    if (op.equals("+")) `
87. `		        temp = n1 + n2; `
88. `		    else if (op.equals("-")) `
89. `		        temp = n1 - n2; `
90. `		    else if (op.equals("/")) `
91. `	  	        temp = n1/n2; `
92. `		    else`
93. `		        temp = n1*n2; `
94. `		    inp.setText(num1+op+num2+" = "+temp); `
95. `		    num1 = Double.toString(temp);`
96. `		    op = num2 = ""; `
97. `	        }`
98. `            }`
99. `	    else`
100. `	    {`
101. `		num1 = op = num2 = ""; `
102. `		inp.setText("");`
103. `	    }`
104. `        } `
105. `	else `
106. `	{ `
107. `	    if (op.equals("") || num2.equals("")) `
108. `		op = button; `
109. `	    else `
110. `	    { `
111. `		double temp;`
112. `		double n1=Double.parseDouble(num1);`
113. `		double n2=Double.parseDouble(num2);`
114. `		if(n2==0 && op.equals("/"))`
115. `		{`
116. `		    inp.setText(num1+op+num2+" = Zero Division Error");`
117. `		    num1 = op = num2 = "";`
118. `		}`
119. `		else`
120. `		{`
121. `		    if (op.equals("+")) `
122. `		        temp = n1 + n2; `
123. `		    else if (op.equals("-")) `
124. `		        temp = n1 - n2; `
125. `		    else if (op.equals("/")) `
126. `	  	        temp = n1/n2; `
127. `		    else`
128. `		        temp = n1*n2; `
129. `		    num1 = Double.toString(temp); `
130. `		    op = button; `
131. `		    num2 = ""; `
132. `	        }`
133. `            }`
134. `	    inp.setText(num1+op+num2);`
135. `        }`
136. `    }`
137. `}`
138. `/*`
139. `<applet code = Calculator.class width=600 height=600>`
140. `</applet>`
141. `*/`

To compile and run the program use the following commands :

```>>>javac Calculator.java
>>>appletviewer Calculator.java```
Program Explanation

1. When any button on the calculator is clicked, the function actionPerformed is called. Get the button clicked using getActionCommand.

2. If the button clicked is a digit or decimal point, then either of the following is executed :
a) The digit is concatenated to the the second number if no operator has been encountered.
b) Otherwise, the digit is concatenated to the first number.

3. If the button clicked is the clear button, then clear the input field.

4. If the button clicked is the equals operator, then either of the following is executed :
a) If neither the first number nor the second number is empty, then compute the result and display it in the frame
b) Otherwise, clear the input field.

5. If any of the button {+,-,*,/} is clicked, then either of the following is executed :
a) If either the operator or the second number is empty, then set the button clicked as the operator.
b) Otherwise, compute the result and display it in the frame.

Runtime Test Cases

Here’s the run time test cases for creating a basic calculator for different input cases.

Test case 1 – To Perform Addition.

Test case 2 – To Perform Subtraction.

Test case 3 – To Perform Multiplication.

Test case 4 – To Perform Division by Non-Zero Value.

Test case 5 – To Perform Division by Zero.

Sanfoundry Global Education & Learning Series – Java Programs.

If you find any mistake above, kindly email to [email protected]