728x90
반복문
중괄호 블록 내용을 반복적으로 실행할 때 사용
종류 : for문, while문, do-while문
for문
반복 횟수를 알고 있을 때 주로 사용
예제)
package sec03.exam03_for;
public class ForPrintForm1To10Example
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++) //i가 1부터 10이 될때까지 반복
{
System.out.println(i);
}
}
}

package sec03.exam03_for;
public class ForSumFrom1To100Example
{
public static void main(String[] args)
{
int sum = 0;
for(int i =1; i<=100; i++)
{
sum += i;
}
System.out.println("1에서 100까지의 합 : "+sum);
}
}

package sec03.exam03_for;
public class ForFloatCounterExample
{
public static void main(String[] args)
{
//카운트 변수를 float타입일때 문제점 : 짜투리 값이 생길 수 있음.
for(float x = 0.1f; x<=1.0f; x+=0.1f)
{
System.out.println(x);
}
}
}

package sec03.exam03_for;
public class ForMultiplicationTableExample
{
public static void main(String[] args)
{
for(int i = 2; i<=9; i++)
{
System.out.println("***"+i+"단***");
for(int j = 1; j<=9; j++)
{
System.out.println(i + " * " + j + " = " + (i*j));
}
}
}
}
출력 결과 값이 너무 길어서 짤렸지만 2단~9단까지 잘 출력되는 것을 확인할 수 있다.

while문
조건에 따라 반복을 계속할지를 결정할 때 사용
예제)
package sec03.exam02_while;
public class WhilePrintForm1To10Example
{
public static void main(String[] args)
{
int i =1;
while(i<=10)
{
System.out.println(i);
i++; //i를 1 증가
}
}
}

package sec03.exam02_while;
public class WhileSumFrom1To100Example
{
public static void main(String[] args)
{
int i = 1;
int sum = 0;
while(i<=100)
{
sum += i;
i++;
}
System.out.println("1에서 100까지의 합은 : "+sum);
}
}

package sec03.exam02_while;
public class WhileKeyControlExample
{
//throws Exception - System.in.read()에서 예외가 발생되면 메인을 실행하는 곳에서 예외처리를 할수 있도록 하기 위해
public static void main(String[] args) throws Exception
{
/*
while(true)
{
//System.in.read() - 키보드의 키코드 값을 리턴받는 함수
int keyCode = System.in.read();
System.out.println(keyCode);
}
1을 입력하면
1
49
13
10
이 출력되는데 13, 10은 1을 입력하고 엔터를 쳤기 때문에 출력되는것 엔터의 키코드가 13,10 이라서
*/
boolean run = true;
int speed = 0;
int keyCode = 0;
//1번 입력후 엔터를 치면 1번 키코드,엔터 키코드 때문에 while문이 3번 돌아야되는데 if를 통해서 한번만 돌도록 만들어준것
while(run) //run이 true일 동안은 계속 반복
{
if(keyCode!=13 && keyCode!=10) //엔터키가 아니라면
{
System.out.println("-----------------------------------");
System.out.println("1.증속 | 2.감속 | 3.중지");
System.out.println("-----------------------------------");
//println은 출력후에 행을 바꾸지만 print는 출력후에 행을 바꾸지 않음
System.out.print("선택:");
}
keyCode = System.in.read();
if(keyCode == 49) //1을 누르면
{
speed ++;
System.out.println("현재 속도 =" + speed);
}
else if(keyCode == 50) //2를 누르면
{
speed --;
System.out.println("현재 속도 =" + speed);
}
else if(keyCode == 51) //3을 누르면
{
run = false; //중지 시키기 위해, while은 run이 true일때만 도니까
}
}
System.out.println("프로그램 종료");
}
}

do-while문
조건에 따라 반복을 계속할지를 결정할 때 사용하는 것은 while문과 동일
무조건 중괄호 { } 블록을 한 번 실행하고, 조건을 검사하여 반복 결정
예제)
package sec03.exam03_dowhile;
import java.util.Scanner;
public class DoWhileExample
{
public static void main(String[] args)
{
System.out.println("메시지를 입력하세요");
System.out.println("프로그램을 종료하려면 q를 입력하세요.");
//키보드로 부터 입력된 문자열을 읽겠다.
//Scanner는 클래스 타입, 사용하기 위해서는 스캐너가 존재하는 패키지를 import해야함
//컨트롤 + 쉬프트 + O 를 누르면 import java.util.Scanner; 이 생성됨
//컴파일러에게 스캐너가 어디있는지 알려줄 수 있음
Scanner scanner = new Scanner(System.in);
String inputString;
do{
//엔터키를 누르기 전까지 입력한 문자열을 얻을 수 있음
inputString = scanner.nextLine();
System.out.println(inputString);
//문자열을 비교하는 메소드
} while(!inputString.equals("q"));
System.out.println();
System.out.println("프로그램 종료");
}
}

break문
for문, while문, do-while문을 종료한다. (반복을 취소한다.)
switch문을 종료한다.
대게 if문과 같이 사용되어 if문의 조건식에 따라 for문과 while문을 종료할 때 사용
예제)
package sec03.exam04_break;
public class BreakExample
{
public static void main(String[] args)
{
while(true)
{
int num = (int)(Math.random()*6) + 1;
System.out.println(num);
if(num==6) //num이 6이면
{
break; //while을 종료
}
}
System.out.println("프로그램 종료");
}
}

반복문이 중첩 되어 있을 경우
반복문이 중첩되어 있을 경우 break문은 가장 가까운 반복문만 종료
바깥쪽 반복문까지 종료시키려면 반복문에 이름(라벨)을 붙이고, "break 이름;" 을 사용
예제)
package sec03.exam04_break;
public class BreakOutterExample
{
public static void main(String[] args)
{
Outter: for(char upper= 'A'; upper<='Z'; upper++)
{
for(char lower = 'a'; lower<='z'; lower++)
{
System.out.println(upper + "_" + lower);
if(lower =='g')
{
//바깥쪽 for문까지 빠져나가게
break Outter;
}
}
}
}
}

continue문
for문, while문, do-while문에서 사용
for문 : 증감식으로 이동
while문, do-while문 : 조건식으로 이동
예제)
package sec03.exam05_continue;
public class ContinueExample
{
public static void main(String[] args)
{
for(int i =1; i<=10; i++)
{
if(i%2 != 0)
{
//반복문의 처음으로 돌아감
continue;
}
System.out.println(i);
}
}
}

728x90
'프로그래밍 언어 > JAVA' 카테고리의 다른 글
[JAVA] 참조 변수의 ==, != 연산 /null과 NullPointerException (0) | 2021.06.11 |
---|---|
[JAVA] 데이터 타입 분류, 메모리 사용 영역 (0) | 2021.06.11 |
[JAVA] 조건문(if문, switch문) (0) | 2021.06.10 |
[JAVA] 코드 실행 흐름 제어 (0) | 2021.06.10 |
[JAVA] 삼항 연산자 (0) | 2021.06.09 |