-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
83 lines (83 loc) · 1.5 KB
/
Calculator.java
File metadata and controls
83 lines (83 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.awt.*;
import java.awt.event.*;
class Calculator extends Frame implements ActionListener
{
TextField tf;
Panel p;
Button b;
int n1,n2,res;
char op;
Calculator( )
{
setSize(300,400);
setVisible(true);
setTitle("Calculator");
setLayout(new BorderLayout( ));
tf=new TextField(25);
add(tf,BorderLayout.NORTH);
p=new Panel(new GridLayout(4,4));
add(p,BorderLayout.CENTER);
String a[ ]={"7","8","9","/","4","5","6","-","1","2","3","*","0","C","=","+"};
for(String i:a)
{
b=new Button(i);
p.add(b);
b.addActionListener(this);
}
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{ System.exit(0);}
});
}
public void actionPerformed(ActionEvent ae)
{
String s=ae.getActionCommand();
if(s.matches("[0-9]"))
{
tf.setText(tf.getText()+s);
}
else if(s.equals("C"))
{
tf.setText("");
}
else if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/"))
{
n1=Integer.parseInt(tf.getText());
op=s.charAt(0);
tf.setText("");
}
else if(s.equals("="))
{
n2=Integer.parseInt(tf.getText());
switch(op)
{
case '+':
res=n1+n2;
break;
case '-':
res=n1-n2;
break;
case '*':
res=n1*n2;
break;
case '/':
try
{
res=n1/n2;
}
catch(ArithmeticException i)
{
tf.setText("Cannot divide by Zero");
return;
}
break;
}
tf.setText(String.valueOf(res));
}
}
public static void main(String args[])
{
new Calculator();
}
}