출처:이것이 자바다
조건문과 반복문
4.1 코드 실행 흐름 제어
=> 정상적인 코드 실행 흐름
main() 메소드의 시작인 중괄호 { 에서 끝 중괄호 } 까지 위-> 아래 방향으로 실행
=> 제어문의 역할
코드 실행 흐름을 개발자가 원하는 방향으로 변경할 수 있도록 도와줌
v 제어문의 종류
조건문
• if 문, switch 문
반복문
• for 문, while 문, do-while 문
break 문, continue 문
제어문의 중첩
제어문의 중괄호 내부에 다른 제어문 작성 가능
• 다양한 흐름 발생 가능
루핑(looping) : 반복문일 경우는 제어문 처음으로 다시 되돌아가 반복 실행한다.
4.2 조건문(if 문 ,switch) 문
4.2.1 if 문
조건식 결과 따라 중괄호 { } 블록을 실행할지 여부 결정할 때 사용
중괄호 블록을 작성하지 않으면 코드의 가독성( 코드 해석) 이 좋지 않고 , 버그 발생의 원인이 될 수 있다.
• true 또는 false 값을 산출할 수 있는 연산식
• boolean 변수
• 조건식이 true 이면 블록 실행하고 false 이면 블록 실행하지 않음
[ IfExample.java ] If 문
public class IfExample {
public static void main(String[] args ) {
int score = 93;
if ( score >= 90) {
System.out .println( " 점수가 90 보다 큽니다 ." );
System.out .println( " 등급은 A 입니다 ." );
}
if ( score < 90)
System.out .println( " 점수가 90 보다 작습니다 ." );
System.out .println( " 등급은 B 입니다 ." );
}
}
4.2.2 if- else 문
조건식 결과 따라 실행 블록 선택
[ IfElseExample.java ] if - else 문
public class IfElseExample {
public static void main(String[] args ) {
int score = 85;
if ( score >= 90) {
System.out .println( "90 보다 크다 " );
System.out .println( "A" );
} else {
System.out .println( "90 아래 " );
System.out .println( "B" );
}
}
}
4.2.3 if- else if -else 문
복수의 조건식 두어 조건식을 만족하는 블록만 실행
[ IfElseIfElseExample .java ]if-else if - else 문
public class IfElseIfElseExample {
public static void main(String[] args ) {
int score = 75;
if ( score > 90) {
System.out .println( " 점수가 100 ~ 90 입니다 ." );
System.out .println( " 등급은 A 입니다 ." );
} else if ( score >= 80) {
System.out .println( " 점수가 80 ~ 89 입니다 ." );
System.out .println( " 등급은 B 입니다 ." );
} else if ( score >= 70) {
System.out .println( " 점수가 70 ~ 79 입니다 ." );
System.out .println( " 등급은 C 입니다 ." );
} else {
System.out .println( " 점수가 70 미만 입니다 ." );
System.out .println( " 등급은 D 입니다 ." );
}
}
}
=>Math.random() 메소드를 활용
이 메소드는 0.0 과 1.0 사이에 속하는 double 타입의 하나를 리턴한다. 0.0 은 범위에 포함되고 1.0 은 범위에 포함되지 않는다.
0.0 <= Math.random() < 1.0
1~ 10 까지 정수중에서 하나의 정수를 얻기
0.0* 10 <= Math.random()* 10 < 1.0 * 10
(0.0) (10.0)
====>int 로 강제 타입변환
(int)0.0* 10 <= Math.random()* 10 < (int)1.0 * 10
0 (0,1,2,3,...9) (10)
1 ~ 10 까지의 정수
(int)0.0* 10 +1 <= Math.random()* 10 < (int)1.0 * 10 +1
1 (1,2,3,...10) (11)
int num = (int) (Math.random()* n)+start;
int num = (int) (Math.random()*6) +1;
int num = (int) (Math.random()*45) +1;
[ IfDiceExample.java ] 주사위의 번호를 뽑는 예제
public class IfDiceExample {
public static void main(String[] args ) {
int num = ( int ) (Math.random () * 6) + 1; // 주사위 번호 하나 뽑기
if ( num == 1) {
System.out .println( "1 번이 나왔습니다 ." );
} else if ( num == 2) {
System.out .println( "2 번이 나왔습니다 ." );
} else if ( num == 3) {
System.out .println( "3 번이 나왔습니다 ." );
} else if ( num == 4) {
System.out .println( "4 번이 나왔습니다 ." );
} else if ( num == 5) {
System.out .println( "5 번이 나왔습니다 ." );
} else {
System.out .println( "6 번이 나왔습니다 ." );
}
}
}
4.2.4 중첩 if 문
코드 실행 흐름을 이해하는 것이 가장 중요
[ IfNestedExample.java ] 중첩 if 문
public class IfNestedExample {
public static void main(String[] args ) {
int score = ( int ) (Math.random () * 20) + 81;
System.out .println( " 점수 : " + score );
String grade ;
if ( score >= 90) {
if ( score >= 95) {
grade = "A+" ;
} else {
grade = "A" ;
}
} else {
if ( score >= 85) {
grade = "B+" ;
} else {
grade = "B" ;
}
}
System.out .println( " 학점 : " + grade );
}
}
4.2.5 switch 문
조건 제어문
변수나 연산식의 값에 따라 실행문 선택할 때 사용
장점 : 비교 대상이 많을 때 if 문 보다 효율적이다.
단점 : 사용이 제한 적이다. ( 실수나 변수 못 쓴다.), 10 < 변수 < 15 와 같은 범위 값에는 쓸수 없다.
case 가 없으면 default 로 가서 실행문을 실행시킨다.
default 는 생략 가능하다.
[ SwitchExample.java ]Switch 문
public class SwitchExample {
public static void main(String[] args ) {
int num = ( int ) (Math.random () * 6) + 1;
switch ( num ) {
case 1:
System.out .println( "1 번이 나왔습니다 ." );
break ;
case 2:
System.out .println( "2 번이 나왔습니다 ." );
break ;
case 3:
System.out .println( "3 번이 나왔습니다 ." );
break ;
case 4:
System.out .println( "4 번이 나왔습니다 ." );
break ;
case 5:
System.out .println( "5 번이 나왔습니다 ." );
break ;
default :
System.out .println( "6 번이 나왔습니다 ." );
break ;
}
}
}
case 끝에 break 가 붙어 있는 이유는 다음 case 를 실행하지 말고 switch 문을 빠져나가기 위해서이다.
break 가 없다면 다음 case 가 연달아 실행되는데, 이때에는 case 값과는 상관없이 실행된다.
[ SwitchNoBreakCaseExample.java ]break 문이 없는 case
public class SwitchNoBreakCaseExample {
public static void main(String[] args ) {
int time = ( int ) (Math.random () * 4) + 8;
System.out .println( "[ 현재시간 : " + time + " 시 ]" );
switch ( time ) {
case 8:
System.out .println( " 출근합나다 ." );
case 9:
System.out .println( " 회의를 합니다 ." );
case 10:
System.out .println( " 업무를 봅니다 ." );
default :
System.out .println( " 외근을 나갑니다 ." );
}
}
}
영어 대소문자에 관계없이 똑같은 알파벳이라면 동일하게 처리하도록 만든 swithc 문이다.
[ SwitchCharExample.java ]char 타입의 Switch 문
public class SwitchCharExample {
public static void main(String[] args ) {
char grade = 'B' ;
switch ( grade ) {
case 'A' :
case 'a' :
System.out .println( " 우수 회원입니다 ." );
break ;
case 'B' :
case 'b' :
System.out .println( " 일반 회원입니다 ." );
break ;
default :
System.out .println( " 손님입니다 ." );
}
}
}
자바 6 까지는 switch 문의 괄호에는 정수 타입(byte, char,short,int, long) 변수나 정수값을 산출하는 연산식만 올 수 있었다.
자바 7 부터는 string 타입의 변수도 올 수 있다.
[ SwitchStringExample.java ]String 타입의 Switch 문
public class SwitchStringExample {
public static void main(String[] args ) {
String position = " 과장 " ;
switch ( position ) {
case " 부장 " :
System.out .println( "700 만원 " );
break ;
case " 과장 " :
System.out .println( "500 만원 " );
break ;
default :
System.out .println( "300 만원 " );
}
}
}
4.3 반복문 (for 문, while 문, do -while 문)
4.3.1 for 문
1 부터 5 까지의 합 :
코드가 간결하면 개발 시간을 줄일 수 있고 , 오류가 날 확률도 줄어든다.
초기화식을 생략할 수 도 있다 .
int i = 0;
for( ; i <= 100; i++){ ....
}
어떤 경우에는 초기화식이 둘 이상이 있을수도 있다.
증감식도 둘 이상이 있을 수 있ㄷ.
이런 경우에는 쉼표(,) 로 구분해서 작성하면 된다.
[ ForSumFrom1To10Example.java ] 부터 10 까지 출력
public class ForSumFrom1To10Example {
public static void main(String[] args ) {
for ( int i = 1; i <= 10; i ++) {
System.out .println( i );
}
}
}
[ ForSumFrom1To100Example.java ]1 부터 100 까지 합을 출력
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 );
}
}
System. out .println( "1 ~ " + i + " 합 : " + sum ); => 이런식으로 하면 오류난다 . i 는 for 문을 벗ㅇ나서는 사용할 수 없기 때문이다 .
1 부터 100 까지의 합을 출력 [ ForSumFrom1To100Example2.java ]i부분 수정
public class ForSumFrom1To100Example2 {
public static void main(String[] args ) {
int sum = 0;
int i = 0;
for ( i = 1; i <= 100; i ++) {
sum += i ;
}
System .out .println( "1 ~ " +( i -1)+ " 합 : " + sum );
}
}
주의할점 : 부동소수점 타입을 사용하지 말아야 한다 .
[ ForFloatCounterExample.java ]float 타입 카운터 변수
public class ForFloatCounterExample {
public static void main(String[] args ) {
for ( float x = 0.1f ; x <= 1.0f ; x += 0.1f) {
System.out .println( x );
}
}
}
구구단 출력하기
public class ForMultiplicationTableExample {
public static void main(String[] args ) {
for ( int m = 2; m <= 9; m ++) {
System.out .println( "*** " + m + " 단 ***" );
for ( int n = 1; n <= 9; n ++) {
System.out .println( m + " x " + n + " = " + ( m * n ));
}
}
}
}
4.3.2 while 문
for 문이 정해진 횟수만큼 반복한다면,while 문은 조건식이 true 일 경우 계속해서 반복한다.
[ WhilePrintFrom1To10Example.java ]1 부터 10 까지 출력
public class WhilePrintFrom1To10Example {
public static void main(String[] args ) {
int i = 1;
while ( i <= 10) {
System.out .println( i );
i ++;
}
}
}
while 문 내에서 계속 누적되는 값을 갖는 변수는 while 문 시작 전에 미리 선언해 놓아야 합니다.
[ WhileSumForm1To100Example.java ]1 부터 100 까지 합을 출력
public class WhileSumForm1To100Example {
public static void main(String[] args ) {
int sum = 0;
int i = 1;
while ( i <=100) {
sum += i ;
i ++;
}
System.out .println( "1~" + ( i -1) + " 합 : " + sum );
}
}
무한 루프는 무한히 반복하여 실행하기 때문에 언젠가는 while 문을 빠져 나가기 위한 코드가 필요하다.
int keyCode = System.in.read();
[ WhileKeyControlExample.java ] 키보드로 while 문 제어
public class WhileKeyControlExample {
public static void main(String[] args ) throws IOException {
boolean run = true ;
int speed = 0;
int keyCode = 0;
while ( run ) {
if ( keyCode != 13 && keyCode != 10) {
System.out .println( "-----------------------------" );
System.out .println( "1. 증속 | 2. 감속 | 3. 중지 " );
System.out .println( "-----------------------------" );
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 변수에 false 를 저장
}
}
System.out .println( " 프로그램 종료 " );
}
}
while 문을 빠져나가기 위한 또 다른 방법으로 break 문을 이용하는 방법도 있다.
System.out.printIn() 메소드는 매개값을 출력하고 다음 행으로 이동.
System.out.print() 메소드는 매개값을 출력만 하고 다음 행으로 이동하지 않는다.
4.3.3 do-while 문
while 문은 시작할 때부터 조건식을 검사하여 블록 내부를 실행할지 결정하지만 , do -while 는 블록 내부의 실행문을 우선 실행시키고 실행 결과에 따라서 반복 실행을 계속할지 결정하는 경우도 발생한다.
조건 따라 반복 계속할지 결정할 때 사용하는 것은 while 문과 동일
무조건 중괄호 { } 블록을 한 번 실행한 후, 조건 검사해 반복 결정
주의할 점은 while() 뒤에 반드시 세미콜론(;) 을 붙어야 한다.
System.in.read() 메소드는 하나의 키 코드만 읽기 때문에 콘솔에 입력된 문자열을 한 번에 읽을 수 없다.
Scanner scanner = new Scanner(System.in);//Scanner 객체 생성
String inputString = scanner.nextLine();//nextLine() 메소드 호출
!inputString.equals("q")
import java.util.Scanner;
[ DoWhileExample.java] do-while 문
public class DoWhileExample {
public static void main(String[] args ) {
System.out .println( " 메시지를 입력하세요 " );
System.out .println( " 프로그램을 종료하려면 q 를 입력하세요 ." );
Scanner scanner = new Scanner(System. in ); // Scanner 객체 생성
String inputString ;
do {
System.out .print( ">" );
inputString = scanner .nextLine(); // 키보드가 입력한 문자열을 얻음
System.out .println( inputString );
} while (! inputString .equals( "q" )); // 문자열을 비교할 때는 equal() 메소드를 사용 .
// q 가 저장되어 있으면 false 가 산출되어 종료
System.out .println();
System.out .println( " 프로그램 종료 " );
scanner .close();
}
}
4.3.4 break 문
for 문, while 문, do-while 문 종료 ( 반복 취소)
Switch 문 종료
대개 if 문과 같이 사용
if 문 조건식에 따라 for 문과 while 문 종료할 때 사용
[ BreakExample.java ]break 로 while 문 종료
public class BreakExample {
public static void main(String[] args ) throws Exception {
while ( true ) {
int num = ( int ) (Math.random () * 6) + 1;
System.out .println( num );
if ( num == 6) {
break ;
}
}
System.out .println( " 프로그램 종료 " );
}
}
반복문이 중첩된 경우
반복문이 중첩되어 있을 경우 break; 문은 가장 가까운 반복문만 종료
바깥쪽 반복문까지 종료시키려면 반복문에 이름( 라벨) 을 붙이고, “break 이름; ” 사용
[ BreakOutterExample.java ] 바깥쪽 반복문 종료
public class BreakOutterExample {
public static void main(String[] args ) throws Exception {
Outter: for ( char upper = 'A' ; upper <= 'Z' ; upper ++) {
for ( char lower = 'a' ; lower <= 'z' ; lower ++) {
System.out .println( upper + "-" + lower );
if ( lower == 'g' ) {
break Outter;
}
}
}
System.out .println( " 프로그램 실행 종료 " );
}
}
4.3.5 continue 문
for 문, while 문, do-while 문에서 사용
for 문: 증감식으로 이동
while 문, do-while 문: 조건식으로 이동
continue 문은 반복문을 종료하지 않고 계속 반복을 수행한다는 점이 break 문과 다르다.
[ ContinueExampl.java ]continue 를 사용한 for 문
public class ContinueExample {
public static void main(String[] args ) throws Exception {
for ( int i = 1; i <= 10; i ++) {
if ( i % 2 != 0) {
continue ;
}
System.out .println( i );
}
}
}
특정 조건을 만족하는 경우에 continue 문을 실행하지 않고 다음 반복으로 넘어간다.
연습문제
1. 조건문과 반복문의 종류를 괄호 ( ) 속에 넣어 보세요.
조건문 : ( if ) , ( switch )
반복문 : ( for ) , ( while ) , ( do - while )
2. 조건문과 반복문을 설명한 것 중 틀린 것은 무엇입니까? (2)
1. if 문은 조건식의 결과에 따라 실행 흐름을 달리할 수 있다.
2. switch 문에서 사용할 수 있는 변수의 타입은 int , double 이 될 수 있다 .
3. for 문은 카운터 변수로 지정한 횟수만큼 반복시킬 때 사용할 수 있다.
4. break 문은 switch 문, for 문, while 문을 종료할 때 사용할 수 있다.
2. switch( 변수 ) {
정수,String
}
3. for 문을 이용해서 1 부터 100 까지의 정수 중에서 3 의 배수의 총합을 구하는 코드를 작성해보세요.
package sec4_example;
public class Exercise03 {
public static void main( String [] args) {
int sum = 0 ;
int i = 0 ;
for (i = 1 ;i <= 100 ;i ++ ) {
if (i% 3 == 0 ) {
sum = sum + i;
}
}
System . out . println ( "3 의 배수의 합 :" + sum);
}
}
3 의 배수의 합 : 1683
4. while 문과 Math.random() 메소드를 이용해서 두 개의 주사위를 던졌을 때 나오는 눈을 ( 눈1, 눈2) 형태로 출력하고, 눈의 합이 5 가 아니면 계속 주사위를 던지고, 눈의 합이 5 이면 실행을 멈추는 코드를 작성해보세요. 눈의 합이 5 가 되는 조합은 (1,4) , (4,1) , (2,3) , (3,2) 입니다.
package sec4_example;
public class Exercise04 {
public static void main( String [] args) {
while ( true ) {
int num1 = ( int ) (Math.random() * 6 ) + 1 ;
int num2 = ( int ) (Math.random() * 6 ) + 1 ;
if (num1 + num2 == 5 ) {
System . out . println ( "(" + num1 + "," + num2 + ")" );
break ;
}
else {
System . out . println ( "(" + num1 + "," + num2 + ")" );
}
}
}
}
( 4 , 4 )
( 1 , 3 )
( 3 , 5 )
( 6 , 2 )
( 1 , 6 )
( 4 , 6 )
( 4 , 2 )
( 4 , 6 )
( 5 , 6 )
( 3 , 6 )
( 4 , 3 )
( 4 , 4 )
( 5 , 6 )
( 3 , 1 )
( 2 , 1 )
( 1 , 2 )
( 1 , 4 )
5. 중첩 for 문을 이용하여 방정식 4x + 5y = 60 의 모든 해를 구해서 (x,y) 형태로 출력해보세요.
단, x 와 y 는 10 이하의 자연수입니다.
package sec4_example;
public class Exercise05 {
public static void main( String [] args) {
for ( int x = 0 ;x <= 10 ;x ++ ) {
for ( int y = 0 ;y <= 10 ;y ++ ) {
if ( 4 * x + 5 * y == 60 ) {
System . out . println ( "(" + x + "," + y + ")" );
}
}
}
}
}
( 5 , 8 )
( 10 , 4 )
6. for 문을 이용해서 실행 결과와 같은 삼각형을 출력하는 코드를 작성해보세요.
package sec4_example;
public class Exercise06 {
public static void main( String [] args)
{
for ( int i = 1 ;i <= 5 ;i ++ )
{
for ( int j = 1 ;j <= i;j ++ )
{
System . out . print ( "*" );
}
System . out . println ();
}
}
}
*
**
***
****
*****
7. while 문과 Scanner 를 이용해서 키보드로부터 입력된 데이터로 예금, 출금, 조회, 종료 기능을 제공하는 코드를 작성해보세요. 이 프로그램을 실행시키면 다음과 같은 실행 결과가 나와야 합니다.
package sec4_example;
import java.util. Scanner ;
public class Exercise07 {
public static void main( String [] args) {
boolean run = true ;
int balance = 0 ;
Scanner scanner = new Scanner ( System . in );
while (run) {
System . out . println ( "-------------" );
System . out . println ( "1. 예금 | 2. 출금 | 3. 잔고 | 4. 종료" );
System . out . println ( "-------------" );
System . out . println ( " 선택> " );
int num = scanner.nextInt();
switch (num) {
case 1 :
System . out . print ( " 예금액>" );
int deposit = scanner.nextInt();
balance += deposit;
break ;
case 2 :
System . out . print ( " 출금액>" );
int withdraw = scanner.nextInt();
balance -= withdraw;
break ;
case 3 :
System . out . println ( " 잔고>" + balance);
break ;
case 4 :
run = false ;
break ;
}
}
System . out . println ( " 프로그램 종료" );
}
}
-------------
1. 예금 | 2. 출금 | 3. 잔고 | 4. 종료
-------------
선택 >
1
예금액 > 10000
-------------
1. 예금 | 2. 출금 | 3. 잔고 | 4. 종료
-------------
선택 >
2
출금액 > 2000
-------------
1. 예금 | 2. 출금 | 3. 잔고 | 4. 종료
-------------
선택 >
3
잔고 > 8000
-------------
1. 예금 | 2. 출금 | 3. 잔고 | 4. 종료
-------------
선택 >
4
프로그램 종료