-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hello.java
116 lines (104 loc) · 2.61 KB
/
Hello.java
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;
public class Hello extends JFrame implements ActionListener {
private JPanel panel;
private JTextField display;
private JButton[] buttons;
private String[] labels = { "Backspace", "", "", "CE", "C", "7", "8", "9",
"/", "sqrt", "4", "5", "6", "x", "%", "1", "2", "3", "-", "1/x",
"0", "-/+", ".", "+", "=", };
private double result = 0;
private String operator = "=";
private boolean startOfNumber = true;
public Hello() {
display = new JTextField(35);
panel = new JPanel();
display.setText("0.0");
display.setEnabled(true);
panel.setLayout(new GridLayout(0, 5, 3, 3));
buttons = new JButton[25];
int index = 0;
for (int rows = 0; rows < 5; rows++)
{
for (int cols = 0; cols < 5; cols++)
{
buttons[index] = new JButton(labels[index]);
if (cols >= 3)
buttons[index].setForeground(Color.red);
else
buttons[index].setForeground(Color.blue);
buttons[index].setBackground(Color.yellow);
panel.add(buttons[index]);
buttons[index].addActionListener(this);
index++;
}
}
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if (command.charAt(0) == 'C')
{
startOfNumber = true;
result = 0;
operator = "=";
display.setText("0.0");
}
else if (command.charAt(0) >= '0' && command.charAt(0) <= '9' || command.equals("."))
{
if (startOfNumber == true)
display.setText(command);
else
display.setText(display.getText() + command);
startOfNumber = false;
}
else
{
if (startOfNumber)
{
if (command.equals("-"))
{
display.setText(command);
startOfNumber = false;
}
else
operator = command;
}
else
{
double x = Double.parseDouble(display.getText());
calculate(x);
operator = command;
startOfNumber = true;
}
}
}
private void calculate(double n)
{
if (operator.equals("+"))
result += n;
else if (operator.equals("-"))
result -= n;
else if (operator.equals("x"))
result *= n;
else if (operator.equals("/"))
result /= n;
else if (operator.equals("="))
result = n;
else if(operator.equals("sqrt"))
result = Math.sqrt(n);
else if(operator.equals("1/x"))
display.setText("" + result);
}
public static void main(String[] args)
{
Hello s = new Hello();
}
}