2024-7-8 네이버 클라우드
반복문이란
어떤 작업을 반복적으로 실행하는 명령어입니다.
< 반복문의 특징 >
현재 조건이 참인 동안만 반복한다.
조건이 거짓이면 반복문 중단, for문을 탈출한다.
반복되는 문장이 1개일 경우에는 "{}" 를 생략해도 된다.
< 반복문의 종류 >
1. for문
2. while문
3. do-while문
For문
반복 횟수가 정확할 때 주로 사용한다.
[ 형식 ]
for(변수 = 초기값 ; 조건 ; 증감값) {
A 조건이 참일때 실행
}
B 조건이 거짓일 때
1. 변수 초기값이 조건에 맞을 경우 for문 안에 문장 실행한다.
변수 = 초기값이 조건에 참일 경우 A 실행
2. for문 앞으로 다시 돌아가서 초기값이 증감값에 따라 변화된 후
변수 = 초기값+ 증감값 이
3. for문 조건에 참일 경우 for문 안에 있는 문장 다시 실행
조건에 참일 경우 A 실행
4. 거짓일 경우 for문 탈출.
조건에 거짓일 경우 B 실행
반복문 변수 선언
한 지역 내(main{})에서 같은 지역변수를 선언하면 안된다.
즉, for문 밖에서 int a를 선언해 주었다면
for문에는 a=0으로 해주어야한다.
int a; //지역변수
for(int a=0; a<10; a++){ // 오류
B
} C
for문 밖에 변수a가 선언되었는데 for문 안에도 변수a 가 선언되어 오류 발생
for(int a=0; a<10; a++){
System.out.println(a);
}
System.out.println(a); // 오류
for문 밖에 변수a가 선언되지 않았는데 불러와서 오류 발생
loal variable (지역변수)
* { 구역 } 안에 선언된 변수
* { 구역 } 을 벗어나면 소멸된다.
따라서,
int a;
for(a=0; a<10; a++){
System.out.println(a);
}
System.out.println(a)
for문 밖에 변수 a 선언해야된다.
[ 구구단 실습 ]
System.in.read()를 이용해 원하는 단을 입력받으면 구구단 출력
package for_;
import java.io.IOException;
public class For02 {
public static void main(String[] args) throws IOException {
System.out.print("원하는 단을 입력 : ");
int dan = System.in.read() -48; //1개의 문자로 받아온다.
for(int i=1;i<10 ; i++) {
System.out.println(dan + " * " + i + " = " + (dan*i));
}
}
}
[실행결과]
원하는 단을 입력 : 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
System.in.read(); 로 원하는 단을 입력받으면
입력한 숫자를 문자로 받아와서 해당 문자를 숫자로 변환해 변수값에 저장이 되기 때문에
숫자와 문자화된 숫자의 차이값인 48을 빼준다.
[입력] 2 -> [기계가 받아온값] 50 -> 50 - 48 -> [출력] 2
[ 저금통 합, 곱 실습 ]
1~10까지의 합을 구하기
package for_;
public class For03 {
public static void main(String[] args) {
int sum=0;
int mul=1; // 곱하기를 할때는 초기값 0으로 설정하면 안된다. - 0으로 결과값 출력됨.
System.out.println("\t합\t곱");
for(int i=1;i<11;i++) {
sum+=i;
mul*=i;
System.out.println(i + "\t" + sum + "\t"+ mul);
}
System.out.println();
System.out.print("\t" + sum);
System.out.print("\t" + mul);
}
}
[실행결과]
합 곱
1 1 1
2 3 2
3 6 6
4 10 24
5 15 120
6 21 720
7 28 5040
8 36 40320
9 45 362880
10 55 3628800
55 3628800
1. 합을 저장할 변수 선언
int sum=0;
2. for문으로 1~10까지 나오는 값의 합을 쌓아가며 변수에 저장
sum = sum + i
sum+= i
3. 곱하기는 초기값이 0으로 설정되어 있으면 결과값이 0으로 출력되기 때문에
0이 아닌 다른 숫자로 초기값을 설정해야한다.
int mul=1;
While문, Do-While문
반복 횟수가 정확하지 않을 때 주로 사용한다. (어떠한 조건이 만족할 때까지 반복하라)
while문과 do-while문은 변수를 whlie문, do-while문 밖에 선언해야 한다.
While문
[ 형식 ]
while(조건) {
증감값;
참 일때
} 거짓
package while_;
public class While01 {
public static void main(String[] args) {
int a=0;
while(a<10) {
a++; // +1
System.out.print(a + " ");
}
System.out.println();
int b=1;
while(true) { // 무한루프 == for(;;)
System.out.print(b + " ");
b++;
if(b > 10) break;
}
}
}
[실행결과]
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
for문으로 무한루프 만드는 방법
[ 형식 ] for( ; ; ) { 코드문장 }
Do - While문
[ 형식 ]
do{
참 일때
}while(조건) ;
거짓
< 루프를 얼마나 돌았는지 COUNT하는 방법 >
변수값을 선언하고 while문 안에 [변수++] 을 해주면
while문이 실행될때 마다 변수에 +1씩 더해서 저장됩니다.
[문제] A ~ Z까지 출력하되 1줄에 7개씩 출력하시오
package while_;
public class DoWhile {
public static void main(String[] args) {
// A B .... X Y Z
char ch ='A';
int count = 0; //(** 몇개 찍혔는지 개수 count)
do {
System.out.print(ch++ + " ");
count++;
if(count%7 == 0) {
System.out.println();
}
}while(ch<='Z') ;
}
}
[실행결과]
A B C D E F G H
I J K L M N O P
Q R ...
[문제] 숫자 맞추기 게임
숫자의 범위는 1~100 사이로 한다.
컴퓨터가 숫자를 발생하면 사용자가 맞추는 프로그램이다.
package while_;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class NumberGame {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
int count = 0;
int num=0;
System.out.print("1 ~ 100 사이의 숫자가 발생했습니다.");
int com = (int)(Math.random()* 100 + 1); // 1부터 100사이의 값을 랜덤으로 가져오기
while(true) {
System.out.println();
System.out.print("숫자 입력 : ");
num = scan.nextInt();
count++;
if(num<com) {
System.out.println(num + "보다 큰 숫자입니다.");
}else if(num>com){
System.out.println(num + "보다 작은 숫자입니다.");
}else{
break;
}
}
System.out.println("딩동댕.. "+count+"번 만에 맞추셨습니다.");
}
}
[실행결과]
1~100 사이의 숫자가 발생했습니다. (87)
숫자 입력 : 50
50보다 큰 숫자입니다.
숫자 입력 : 95
95보다 작은 숫자입니다.
~~
숫자 입력 : 87
딩동댕.. x번 만에 맞추셨습니다.
다중 for문
for문 안에 또 다른 for문이 존재하는 것
for문에 사용되는 변수명은 서로 달라야 하며 겹쳐서도 안된다.
[문제] 2단 ~ 9단까지 3개씩 끊어서 출력하시오
package multiFor;
public class MultiFor04 {
public static void main(String[] args) {
int dan, i;
int count=0;
int line;
for(line=2; line<10; line+=3) { // 단이 한 줄에 3개씩만 출력되도록
for(i=1; i<10;i++) {
for(dan=line; dan<line+3; dan++) { // 단
if(dan==10) { // dan이 10일때 for문 나간다.
break;
} else if(dan>7) { //dan이 8이상은
System.out.print(dan+"*"+i+"="+(dan*i)+"\t");
count++;
if(count%2==0) { // 한 줄에 2개 나오면 줄바꿈하기
System.out.println();
}
}else { // 그 외는
System.out.print(dan+"*"+i+"="+(dan*i)+"\t");
count++;
if(count%3==0) { //한줄에 3개씩 출력
System.out.println();
}
}
}
}System.out.println();
}
}
}
[실행결과]
2*1=2 3*1=3 4*1=4
2*2=4 3*2=6 4*2=8
2*3=6 3*3=9 4*3=12
2*4=8 3*4=12 4*4=16
2*5=10 3*5=15 4*5=20
2*6=12 3*6=18 4*6=24
2*7=14 3*7=21 4*7=28
2*8=16 3*8=24 4*8=32
2*9=18 3*9=27 4*9=36
5*1=5 6*1=6 7*1=7
5*2=10 6*2=12 7*2=14
5*3=15 6*3=18 7*3=21
5*4=20 6*4=24 7*4=28
5*5=25 6*5=30 7*5=35
5*6=30 6*6=36 7*6=42
5*7=35 6*7=42 7*7=49
5*8=40 6*8=48 7*8=56
5*9=45 6*9=54 7*9=63
8*1=8 9*1=9
8*2=16 9*2=18
8*3=24 9*3=27
8*4=32 9*4=36
8*5=40 9*5=45
8*6=48 9*6=54
8*7=56 9*7=63
8*8=64 9*8=72
8*9=72 9*9=81
Break
break는 반복문(for, while, do~while), switch를 벗어날 때 사용된다.
break는 자신(break)이 속해있는 반복문만 벗어난다.
[ 형식 ]
while(true){
for(조건) {
break;
} // 탈출
// 다시 while문 반복
}
여러 개의 반복문을 벗어나고 싶을 경우, 라벨을 이용해 벗어난다.
[ 형식 ]
loop : while(true){
for(조건) {
break Loop;
} // 탈출
// 탈출
}
Continue
실행문 조건일 경우 다음 문장들은 무시하고 다시 while문 반복한다.
int a = 0;
while(a<=5){
if(a==3) {
continue; //실행문 조건일 경우 패스 하고 while문으로 다시 올라감
}
System.out.println(a)
}
[실행결과]
0
1
2
4
5
a가 3일때 아래로 더 가지 않고 다시 while문 젤 위로 이동
'Java' 카테고리의 다른 글
Java, Array 배열이란? (1차원 배열 - 배열 크기 .length, 홀수, 짝수, 오름차순 .sort, 확장 for문 ) (0) | 2024.07.09 |
---|---|
Java, 컴퓨터 게임(덧셈 계산 게임) / Math.random(), for문 , while문, 다중 for문 (0) | 2024.07.08 |
Java, System.in.read(); 사용자 입력 명령어 (0) | 2024.07.08 |
Java, 조건문 If문 / Switch문 형 (0) | 2024.07.08 |
Java, 연산자(최우선, 산술, 관계, 논리, 조건, 증감, 대입, 부정, 비트) (0) | 2024.07.08 |