-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculator2.java
360 lines (311 loc) · 8.34 KB
/
Calculator2.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
* Author: Sean Moen
* A class to create a window for a simple calculator that takes an input of natural numbers
* with support for binary addition, subtraction, multiplication, division
* and a square root function.
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Calculator2 extends JFrame implements ActionListener
{
private final int NUM_BUTTONS = 18;
private JButton buttons[] = new JButton[NUM_BUTTONS];
//constants for button captions
private final String S_ONE = "1";
private final String S_TWO = "2";
private final String S_THREE = "3";
private final String S_FOUR = "4";
private final String S_FIVE = "5";
private final String S_SIX = "6";
private final String S_SEVEN = "7";
private final String S_EIGHT = "8";
private final String S_NINE = "9";
private final String S_ZERO = "0";
private final String S_PLUS = "+";
private final String S_MINUS = "-";
private final String S_MULTIPLY = "*";
private final String S_DIVIDE = "/";
private final String S_RESULT = "=";
private final String S_RESET = "AC";
private final String S_SQRT = "sqrt";
private final String S_BACKSPACE = "del";
//constants for error messages
private final String ERROR_INVALID_INPUT = "ERROR: INVALID INPUT";
private final String ERROR_DIVIDE_BY_ZERO = "ERROR: DIVIDE BY ZERO";
private final String ERROR_IMAGINARY_NUMBER = "ERROR: RESULT IS IMAGINARY";
//
private String captions[] = {
S_ONE, S_TWO, S_THREE, S_FOUR,
S_FIVE, S_SIX, S_SEVEN, S_EIGHT,
S_NINE, S_ZERO, S_SQRT, S_BACKSPACE,
S_PLUS, S_MINUS, S_MULTIPLY, S_DIVIDE,
S_RESET, S_RESULT
};
private JPanel buttonPanel = new JPanel(new GridLayout(5, 4));
private JTextField output = new JTextField(20);
Container frame;
private String input;
/**
* Initializes the calculator, creating a window with a textfield
* to display input and output. Also creates a button panel from
* with buttons from the captions String and assigns a listener
* to each button.
*/
public Calculator2()
{
input = new String();
frame = getContentPane();
for (int count = 0; count < buttons.length; count++)
{
buttons[count] = new JButton(captions[count]);
buttonPanel.add(buttons[count]);
buttons[count].addActionListener(this);
}
frame.setLayout(new BorderLayout());
frame.add(output, BorderLayout.NORTH);
frame.add(buttonPanel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
/**
* Includes all event handling by checking the source of the action.
* Simple Inputs (e.g. "1" and "del") are handled entirely in here.
* Other event handlers use helper functions.
* Sets the textfield to the value of input, except for
* result and sqrt which instead set the textfield to the result
*/
public void actionPerformed(ActionEvent ae)
{
//1
if(ae.getSource() == buttons[0])
{
input = input + 1;
}
//2
if(ae.getSource() == buttons[1])
{
input = input + 2;
}
//3
if(ae.getSource() == buttons[2])
{
input = input + 3;
}
//4
if(ae.getSource() == buttons[3])
{
input = input + 4;
}
//5
if(ae.getSource() == buttons[4])
{
input = input + 4;
}
//6
if(ae.getSource() == buttons[5])
{
input = input + 6;
}
//7
if(ae.getSource() == buttons[6])
{
input = input + 7;
}
//8
if(ae.getSource() == buttons[7])
{
input = input + 8;
}
//9
if(ae.getSource() == buttons[8])
{
input = input + 9;
}
//0
if(ae.getSource() == buttons[9])
{
input = input + 0;
}
//backspace
if(ae.getSource() == buttons[11])
{
if(!input.isEmpty())
{
input = input.substring(0, input.length() - 1);
}
}
//+
if(ae.getSource() == buttons[12])
{
if(isOperatorAddable())
{
input = input + "+";
}
}
//-
if(ae.getSource() == buttons[13])
{
if(isOperatorAddable())
{
input = input + "-";
}
}
//*
if(ae.getSource() == buttons[14])
{
if(isOperatorAddable())
{
input = input + "*";
}
}
// "/"
if(ae.getSource() == buttons[15])
{
if(isOperatorAddable())
{
input = input + "/";
}
}
//reset
if(ae.getSource() == buttons[16])
{
resetInput();
}
//Updates the textfield with the input, if result or sqrt is called
//then it will set it again to their output
output.setText(input);
//=
if(ae.getSource() == buttons[17])
{
output.setText(getResult());
resetInput();
}
//sqrt
if(ae.getSource() == buttons[10])
{
output.setText(getSqrt());
resetInput();
}
}
/*
* Sets the input to an empty string.
*/
private void resetInput()
{
input = new String();
}
/*
* Checks if adding an operator to the input would ensure a binary operation
* by checking if the input is not empty and that there is currently no operator currently present.
* @return true if an operator can be added to ensure a binary operation, returns false otherwise
*/
private boolean isOperatorAddable()
{
//check if input is not empty and if it doesn't contain an operator
if(input.isEmpty())
return false;
if(input.contains("+") || input.contains("-")
|| input.contains("*") || input.contains("/"))
{
return false;
}
return true;
}
/**
* Returns the result of the equation or an error message.
* Returns an empty string if the input is empty
* If there is only one operand, returns the operand. Needed for implementation of sqrt
* For a binary equation returns the result or error message for division by zero.
* If there is an error in input, an invalid input error is returned.
* @return A string containing the result of the equation, or an appropriate error message.
*/
private String getResult()
{
//if empty, nothing needs to be done
if(input.isEmpty())
return "";
//if an operator can be added, that means there isn't a problem to be solved
//but if its not empty, then the input is equal to itself
if(isOperatorAddable())
return input;
//find operator
char operator = getOperator();
int operatorPos = input.indexOf(operator);
if(input.substring(operatorPos + 1).equals(""))
return ERROR_INVALID_INPUT;
//find operands - substrings are needed since parseInt only works on numerical strings
int leftOperand = Integer.parseInt(input.substring(0, operatorPos));
int rightOperand = Integer.parseInt(input.substring(operatorPos + 1));
//calculate result
if(operator == '+')
return "" + (leftOperand + rightOperand);
if(operator == '-')
return "" + (leftOperand - rightOperand);
if(operator == '*')
return "" + (leftOperand * rightOperand);
if(operator == '/')
{
if(rightOperand == 0)
return ERROR_DIVIDE_BY_ZERO;
return "" + ((double)leftOperand / rightOperand);
}
//This should never happen
return "How did we get here??";
}
/**
* Returns the operator in input.
* @return the operator in input
*/
private char getOperator()
{
if(input.contains("+"))
return '+';
if(input.contains("-"))
return '-';
if(input.contains("*"))
return '*';
if(input.contains("/"))
return '/';
return 'a';
}
/**
* Returns the square root of the current input.
* Can take a unary input or binary input.
* Returns an error message on invalid input or if result is imaginary.
* @return A string of the square root of the current input or an error message
*/
private String getSqrt()
{
//get the result
String operandString = getResult();
if(operandString.equals(""))
return "";
double operand;
try
{
operand = Double.parseDouble(operandString);
}
catch(NumberFormatException e)
{
return ERROR_INVALID_INPUT;
}
//check if
if(!(operand > 0))
return ERROR_IMAGINARY_NUMBER;
return "" + Math.sqrt(operand);
}
/**
* Returns the current input string.
*/
public String toString()
{
return input;
}
public static void main(String[] arguments)
{
Calculator2 c = new Calculator2();
}
}