본문 바로가기
Java

[Java 자바] 반복문

by sycareer 2021. 4. 25.

1. for

2. while

3. do-while

 

 

 

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
package com.sy.practice1.example;
 
import java.util.Scanner;
 
public class E_LoopPractice {
    
    //반복문 실습
    
    //반복문1. 1부터 입력받은 정수까지 모두 출력(for문)
    //         (단, 입력한 수는 1보다 크거나 같음)
    public void practice1() {
        //데이터 입력
        Scanner sc = new Scanner(System.in);
        
        System.out.print("1이상의 정수를 입력하세요 : ");
        int num = sc.nextInt();
        
        //1이상의 정수인지 확인(if문)
        //1 2 3 4 ... 출력(for문)
        if (num >= 1) {
            for (int i = 1; i <= num; i++) {
                System.out.print(i + " ");
            }
        } else {
            System.out.println("잘못 입력하셨습니다.");
        }
    }
    
    
    //반복문2. practice1과 동일하며, 1미만 숫자 입력시 다시 입력할 수 있도록 처리
    public void practice2() {
        //데이터 입력
        Scanner sc = new Scanner(System.in);
        //while문으로 반복실행
        while (true) {
            System.out.print("1이상의 정수를 입력하세요 : ");
            int num = sc.nextInt();
            
            //1이상의 정수인지 확인(if문)
            //1 2 3 4 ... 출력(for문)
            if (num >= 1) {
                for (int i = 1; i <= num; i++) {
                    System.out.print(i + " ");
                }
                return;        //정상적인 숫자 입력시 아래의 메시지 출력되지 않도록 메소드 종료.
            } else {
                System.out.println("잘못 입력하셨습니다. 다시 입력해주세요.");
            }
        }
    }
    
    
    //반복문3. 1부터 입력받은 정수까지 모든 숫자 거꾸로 출력.(for문)
    //         (단, 입력한 수는 1보다 크거나 같음)
    public void practice3() {
        //데이터 입력
        Scanner sc = new Scanner(System.in);
        
        System.out.print("1이상의 정수를 입력하세요 : ");
        int num = sc.nextInt();
        
        //1이상의 정수인지 확인(if문)
        //4 3 2 1 ... 출력(for문)
        if (num >= 1) {
            for (int i = num; i >= 1; i--) {
                System.out.print(i + " ");
            }
        } else {
            System.out.println("잘못 입력하셨습니다.");
        }
    }
    
    
    //반복문4. practice3과 동일하며, 1미만 숫자 입력시 다시 입력할 수 있도록 처리
    public void practice4() {
        //데이터 입력
        Scanner sc = new Scanner(System.in);
        //while문으로 반복실행
        while (true) {
            System.out.print("1이상의 정수를 입력하세요 : ");
            int num = sc.nextInt();
            
            //1이상의 정수인지 확인(if문)
            //4 3 2 1 ... 출력(for문)
            if (num >= 1) {
                for (int i = num; i >= 1; i--) {
                    System.out.print(i + " ");
                }
                return;        //정상적인 숫자 입력시 아래의 메시지 출력되지 않도록 메소드 종료.
            } else {
                System.out.println("잘못 입력하셨습니다. 다시 입력해주세요.");
            }
        }
    }
    
    
    //반복문5. 1부터 입력받은 정수까지의 합 출력
    public void practice5() {
        //데이터 입력
        Scanner sc = new Scanner(System.in);
        
        System.out.println("정수를 하나 입력하세요 : ");
        int num = sc.nextInt();
        
        int sum = 0;
        
        for (int i = 1; i <= num; i++) {
            sum += i;        //1부터 입력받은 정수까지의 합
            if (i < num) {
                System.out.print(i + " + ");
            } else {
                System.out.print(i + " = " + sum);
            }
        }
    }
    
    
    //반복문6. 입력받은 두 개의 정수 포함하여 두 정수 사이의 숫자 모두 출력(for문)
    //         1미만의 숫자 입력되는 경우 1이상 숫자 입력하라는 메시지 출력
    public void practice6() {
        //데이터 입력
        Scanner sc = new Scanner(System.in);
        
        System.out.print("첫 번째 숫자 : ");
        int num1 = sc.nextInt();
        
        System.out.print("두 번째 숫자 : ");
        int num2 = sc.nextInt();
        
        //1이상인지 검사
        if ((num1 < 1|| (num2 < 1)) {
            System.out.println("1이상의 숫자만을 입력해주세요.");
        } else {
            //큰 값이 먼저 입력되어도 작은 값부터 출력되도록 처리
            /*
            if (num1 < num2) {
                for (int i = num1; i <= num2; i++) {
                    System.out.print(i + " ");
                }
            } else {
                for (int i = num2; i <= num1; i++) {
                    System.out.print(i + " ");
                }
            }
            */
            
            int min = Math.min(num1, num2);        //최솟값 : math.min(변수, 변수);
            int max = Math.max(num1, num2);        //최댓값 : math.max(변수, 변수);
            
            for (int i = min; i <= max; i++) {
                System.out.print(i + " ");
            }
            return;        //정상적인 숫자 입력시 아래의 메시지 출력되지 않도록 메소드 종료.
        }
    }
    
    
    //반복문7. practice6과 동일하며, 1미만 숫자 입력시 다시 입력할 수 있도록 처리
    public void practice7() {
        //데이터 입력
        Scanner sc = new Scanner(System.in);
        //다시 실행되도록 do-while문 사용
        do {
            System.out.print("첫 번째 숫자 : ");
            int num1 = sc.nextInt();
            
            System.out.print("두 번째 숫자 : ");
            int num2 = sc.nextInt();
            
            //1이상인지 검사
            if ((num1 < 1|| (num2 < 1)) {
                System.out.println("1이상의 숫자만을 입력해주세요.");
            } else {
                //큰 값이 먼저 입력되어도 작은 값부터 출력되도록 처리
                /*
                if (num1 < num2) {
                    for (int i = num1; i <= num2; i++) {
                        System.out.print(i + " ");
                    }
                    return;        //정상적인 숫자 입력시 아래의 메시지 출력되지 않도록 메소드 종료.
                } else {
                    for (int i = num2; i <= num1; i++) {
                        System.out.print(i + " ");
                    }
                    return;        //정상적인 숫자 입력시 아래의 메시지 출력되지 않도록 메소드 종료.
                }
                */
                
                int min = Math.min(num1, num2);        //최솟값 : math.min(변수, 변수);
                int max = Math.max(num1, num2);        //최댓값 : math.max(변수, 변수);
                
                for (int i = min; i <= max; i++) {
                    System.out.print(i + " ");
                }
                return;        //정상적인 숫자 입력시 아래의 메시지 출력되지 않도록 메소드 종료.
            }    
        } while (true);
    }
    
    
    //반복문8. 입력받은 정수에 해당하는 구구단 출력(for문)
    public void practice8() {
        //데이터 입력
        Scanner sc = new Scanner(System.in);
        
        System.out.print("숫자 : ");
        int num = sc.nextInt();
        
        //구구단 출력
        System.out.println("===== " + num + "단 =====");
        
        //1~9까지 뒤에 곱해질 숫자 반복 출력
        for (int i = 1; i <= 9; i++) {
            System.out.println(num + " * " + i + " = " + (num * i));
        }
    }
    
    
    //반복문9. 입력받은 정수에 해당하는 단부터 9단까지 출력(for문)
    //         (2~9 사이의 숫자가 아닌 경우 안내메시지 출력)
    public void practice9() {
        //데이터 입력
        Scanner sc = new Scanner(System.in);
        
        System.out.print("숫자 : ");
        int num = sc.nextInt();
        
        if ((num < 2|| (num > 9)) {
            System.out.println("2~9 사이의 숫자만 입력해주세요.");
        } else {
            //해당 숫자 ~ 9단까지 반복
            for (int j = num; j <= 9; j++) {
                //구구단 출력
                System.out.println("===== " + j + "단 =====");
            
                //1~9까지 뒤에 곱해질 숫자 반복 출력
                for (int i = 1; i <= 9; i++) {
                    System.out.println(j + " * " + i + " = " + (j * i));
                }
            }
        }
    }
    
    
    //반복문10. practice9와 동일하며, 2~9사이 아닌 숫자 입력시 다시 입력할 수 있도록 처리
    public void practice10() {
        //데이터 입력
        Scanner sc = new Scanner(System.in);
        
        //while문으로 잘못된 숫자 입력시 반복 실행
        while(true) {
            System.out.print("숫자 : ");
            int num = sc.nextInt();
            
            if ((num < 2|| (num > 9)) {
                System.out.println("2~9 사이의 숫자만 입력해주세요.");
            } else {
                //해당 숫자 ~ 9단까지 반복
                for (int j = num; j <= 9; j++) {
                    //구구단 출력
                    System.out.println("===== " + j + "단 =====");
                
                    //1~9까지 뒤에 곱해질 숫자 반복 출력
                    for (int i = 1; i <= 9; i++) {
                        System.out.println(j + " * " + i + " = " + (j * i));
                    }
                }
                return;        //정상적인 숫자 입력시 아래의 메시지 출력되지 않도록 메소드 종료.
            }
        }
    }
    
    
    //반복문11. 시작 숫자와 공차를 입력받아 연산(for문)
    //          총 10개의 숫자 출력되도록
    public void practice11() {
        //데이터 입력
        Scanner sc = new Scanner(System.in);
        
        System.out.print("시작 숫자 : ");
        int num1 = sc.nextInt();
        
        System.out.print("공차 : ");
        int num2 = sc.nextInt();
        
        /*
        for (int i = num1; i <= (num1 + num2 * 9); i += num2) {
            System.out.print(i + " ");
        }
        */
        
        for (int i = 1; i <= 10; i++) {
            System.out.print(num1 + " ");
            num1 += num2;
        }
        
    }
    
    
    //반복문12. 연산자, 정수 두 개 입력받고, 
    //          연산자가 나누기이고 두 번째 정수가 0이면, 0으로 나눌수 없다고 메시지 출력 후 다시 실행
    //          연산자에 exit입력시 프로그램 종료.
    public void practice12() {
        
        Scanner sc = new Scanner(System.in);
        
        while (true) {
            System.out.print("연산자(+,-,*,/,%) : ");
            String oper = sc.nextLine();
 
            if (oper.equals("exit")) {
                System.out.println("프로그램을 종료합니다.");
                return;
            }
            
            System.out.print("정수1 : ");
            int num1 = sc.nextInt();
            
            System.out.print("정수2 : ");
            int num2 = sc.nextInt();
            sc.nextLine();
 
            int result = 0;
            
            if ((oper.equals("/")) && (num2 == 0)) {
                System.out.println("0으로 나눌 수 없습니다. 다시 입력해주세요. \n");
                continue;        //아래의 코드 실행하지 않고 바로 반복문 다시 처음부터 실행
            }
            
            switch (oper) {
            case "+":
                result = num1 + num2; break;
            case "-":
                result = num1 - num2; break;
            case "*":
                result = num1 * num2; break;
            case "/":
                result = num1 / num2; break;
            case "%":
                result = num1 % num2; break;
            default:
                System.out.println("없는 연산자입니다. 다시 입력해주세요.");    
                continue;        //아래의 코드 실행하지 않고 바로 반복문 다시 처음부터 실행
            }
            System.out.printf("%d %s %d = %d\n", num1, oper, num2, result);
            System.out.println();
            }
    }
    
}
 
cs

'Java' 카테고리의 다른 글

자바 요약 정리 - 연산자  (0) 2021.07.06
자바 요약 정리 - 변수  (0) 2021.07.06
[Java 자바] 조건문  (0) 2021.04.25
[Java 자바] 연산자  (0) 2021.04.25
[Java 자바] 형변환 - 자동 형변환, 강제 형변환  (0) 2021.04.25