JAVA 계산기(calculator) 예제

자바 스윙을 이용한 계산기 예제

자료형의 수정 보완과 괄호처리를 해야지만..



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
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
 
public class J1221_Calculator extends JFrame{
    
    public JButton[] bt = new JButton[18];
    public JTextField textField;
    
    int xpos = 30;
    int ypos = 100;
    
    int temp = 3;
    
    public J1221_Calculator(){
        
        setTitle("계산기");
        setSize(300,400);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JPanel panel = new JPanel();
        add(panel);
        panel.setLayout(null);
        
        // 버튼
        for(int i = 0; i<bt.length-4; i++){
            bt[i] = new JButton(" ");
            bt[i].setBounds(xpos, ypos, 5030);
            bt[i].addActionListener(new Subclass());
            panel.add(bt[i]);
            
            xpos += 60;
            temp--;
            
            if(temp%== 0){
                xpos = 30;
                ypos = ypos + 40;
                temp = 3;
            }
            
            if(i == 12) bt[i].setBounds(3026011030);
            if(i == 13) bt[i].setBounds(15026050,30);
        }
        
        xpos = 210;
        ypos = 140;
        
        for(int i =14;i<bt.length; i++){
            bt[i] = new JButton(" ");
            bt[i].setBounds(xpos,ypos,50,30);
            bt[i].addActionListener(new Subclass());
            panel.add(bt[i]);
            ypos += 40;
        }
        
        bt[0].setText("←");
        bt[1].setText("C");
        bt[2].setText("=");
        bt[13].setText(".");
        bt[14].setText("/");
        bt[15].setText("*");
        bt[16].setText("-");
        bt[17].setText("+");
        
        for(int i =3; i<13; i++){
            bt[i].setText(Integer.toString(i-2));
            if(i == 12){
                bt[i].setText("0");
            }
        }
        
        // textField 생성
        textField = new JTextField();
        textField.setBounds(305022030);
        panel.add(textField);
        
    }
    
    // 메인
    public static void main(String args[]){
        new J1221_Calculator();
    }
    
    // Button funtion
    class Subclass implements ActionListener{
    
        JButton jb;
        
        String tempSt;
        char tempC;
        int tempInt;
        char[] tempArray; // 동적할당됨
        
        ArrayList<Integer> it = new ArrayList<>(); // 객체 배열
        
        // 버튼의 기능들
        public void actionPerformed(ActionEvent e){
            
            jb = (JButton)e.getSource();
            
            // 형변환
            tempC = jb.getText().charAt(0); // 문자 하나일때만 가능
            tempInt = (int)tempC;
            
            // 아스키코드조건에 맞는다면 함수호출
            // 단순 값을 텍스트에 입력
            if(tempInt>41 && tempInt<58) keyReturn(jb.getText());
            // 'C' 클리어 버튼
            if(tempInt == 'C'){
                textField.setText(null);
            }
            // <- 뒤로 삭제 버튼
            if(jb.getText().equals("←")){
 
                tempSt = textField.getText();
                
                // 둘다 참일때 참을 리턴 
                // 앞이 거짓이면 뒤를 검사하지 않음
                // null 이 아니지만 비어있을경우 isEmpty로 검사함
                // strlength() == 0 일 경우도 검사가능
                if(tempSt != null && !tempSt.isEmpty()){
                    tempSt = tempSt.substring(0,tempSt.length()-1);
                    textField.setText(tempSt);
                }
            }
            // '=' 계산
            if(jb.getText().equals("=")){
                
                Cal();
                
                System.out.println("it : "+it);
                
            }
        }
        // 계산
        public void Cal(){
            
            // 일시적으로 배열에 숫자를 넣음
            char[] tempNumber = new char[10];
            
            // it객체 계산 변수
            int result;
            
            int count = 0;
            
            // String값을 char 배열로 받음
            tempArray = (textField.getText()).toCharArray();
            
            for(int i = 0; i<tempArray.length; i++){
                
                // i가 0번째일때 
                if(i == tempArray.length-1){
                    
                    // 마지막일때 예외로 tempNumber에 값을 넣어야됨
                    tempNumber[count] = tempArray[i]; 
                    // 숫자배열 숫자로 만들기위한 Number 호출
                    Number(tempNumber);
                    
                    //초기화
                    for(int j =0; j<tempNumber.length; j++){
                        tempNumber[j] = '\0';
                    }
                    count = 0;
                    continue;
                }
                
                // 연산자가 나올때
                if((int)tempArray[i] == '/' || (int)tempArray[i] == '*' || (int)tempArray[i] == '+' || (int)tempArray[i] == '-') {
                    
                    Number(tempNumber);
                    // 배열리스트에 add
                    it.add((int)tempArray[i]);
                    
                    //초기화
                    for(int j =0; j<tempNumber.length; j++){
                        tempNumber[j] = '\0';
                    }
                    count = 0;
                    continue;
                }
                tempNumber[count] = tempArray[i];
                count++;
            }
            // 마지막 계산 i가 0일때 *,/ 계산 2일때 +,- 계산
            for(int i =0; i<2; i++){
                
                for(int j =it.size()-1; j>=0; j--){
                    
                    if(i == 0){
                        switch(it.get(j)){
                            case 42 :
                                result = it.get(j-1* it.get(j+1);
                                
                                it.add(j-1, result);
                                
                                // 뒤에부터 없어지니까 for로 j만 3번 없애도됨
                                it.remove(j+2);
                                it.remove(j+1);
                                it.remove(j);
                                
                                break;
                            case 47 :
                            
                                result = it.get(j-1/ it.get(j+1);
                                
                                it.add(j-1, result);
                                
                                it.remove(j+2);
                                it.remove(j+1);
                                it.remove(j);
                                
                                break;
                        }
                    }
                    else{
                        switch(it.get(j)){
                            case 43 :
                                result = it.get(j-1+ it.get(j+1);
                                
                                it.add(j-1, result);
                                
                                it.remove(j+2);
                                it.remove(j+1);
                                it.remove(j);
                                
                                break;
                            case 45 :
                            
                                result = it.get(j-1- it.get(j+1);
                                
                                it.add(j-1, result);
                                
                                it.remove(j+2);
                                it.remove(j+1);
                                it.remove(j);
                                
                                break;
                        }
                    }
                }
            }
            // 결과값을 보냄
            textField.setText(Integer.toString(it.get(0)));
            // 초기화시킴
            it.remove(0);
        }
        
        // 숫자배열을 숫자로 만드는 함수
        public void Number(char[] numberArray){            
            int count=10;
            int sum = 0;
            int size = 0;
            for(int i=0; i<numberArray.length; i++){
                if(numberArray[i] =='\0'break;
                size++;
            }
            // 숫자를 구함
            for(int i= 0; i<size; i++){
                sum = (sum*count) + ((int)numberArray[i]-'0');
            }
            // it에 add시킴
            it.add(sum);
        }
        // 입력 키를 textField에 리턴함
        public void keyReturn(String key){
            tempSt = textField.getText();
            tempSt = tempSt + key;
            textField.setText(tempSt);
            check(tempSt);
        }
        // 예외처리
        public void check(String a){
            tempArray = a.toCharArray(); // 배열 복사
            // 첫번째에 연산자나 소수점이 안들어오게함.
            if(((int)tempArray[0]>41 && (int)tempArray[0]<48|| tempArray[0== '.'){
                textField.setText(null);
            }
            if(tempArray.length > 2){
                tempInt = (int)tempArray[tempArray.length-1];
                tempInt2 = (int)tempArray[tempArray.length-2];
                // 연산자예외 처리
                if((tempInt>41 && tempInt<48&& (tempInt2>41 && tempInt2<48)){
                    a = a.substring(0,a.length()-1);
                    textField.setText(a);
                }
                // 소수예외 처리
                if(tempInt == '.'){
                    // 두번째부터 시작함]
                    for(int i = tempArray.length-2; i>0; i--){
                        int aa = (int)tempArray[i];
                        
                        // 숫자에 이미 소수점이 있다면
                        if(aa == '.'){
                            a = a.substring(0,a.length()-1);
                            
                            textField.setText(a);
                        }
                        // 중간에 연산자가 있으면 break
                        else if(aa>41 && aa<48break;                        
                    }
                }
            }
        }
    }
}
cs

댓글