1) 조건문
조건문은 특정 조건을 만족하거나 하지 않을 때 수행할 작업을 미리 정해놓고, 조건에 따라 각각 결과를 반환한다.
단, 조건문은 중복선택이 불가능하다. 조건에 맞는 답이 두가지가 될 수 없다.
1-1) if문
if 문은 조건식 부분과 실행부분으로 나누어진다. if 문의 형태는 다음과 같다.
if(조건식)
{
//실행할 내용
}
여기서 조건식에 들어갈 값은 무조건 비교연산자나 boolean 값으로 나타낼 수 있는 참 또는 거짓의 값이여야 한다.
예를 들자면 예나 아니오로 대답할 수 있는 질문만 하는것이 조건식이다.
"생일이 언제입니까?", "성함이 어떻게 되십니까?" 와 같이 예나 아니오로 답변할 수 없는 질문은 조건식이 될 수 없다.
"생일이 3월보다 늦습니까?", "이름이 홍길동씨 입니까?" 와 같이 예나 아니오로 답변할 수 있는 질문은 조건식이 될 수 있다.
이후 나오는 if문들은 if문의 확장된 형태이다.
1-2) if - else 문
if - else문은 if문이 조건에 맞지않아 실행되지 않았을 때 else를 실행한다. if - else문의 형태는 다음과 같다.
if(조건식)
{
//실행할 내용 => 조건식이 true 일때 실행 됨
}
else
{
//실행할 내용 => 조건식이 false 일때 실행 됨
}
여기서 확인해볼것은 else 문에는 조건이 붙지 않는다. 왜냐하면 if 의 조건식이 false면 무조건 else가 실행 되므로 추가적인 조건이 필요없다.
public static void main(String[] args)
{
int age;
Scanner input = new Scanner(System.in);//새 스캐너 주소를 input에 넣고
System.out.println("연령을 입력해주세요 : ");
age = input.nextInt();//input안의 nextInt을 불러온다
if(age>19)
{
System.out.println("성인 입니다.");
System.out.println("성인 요금이 청구됩니다.");
}
else
{
System.out.println("비성인 입니다.");
System.out.println("비성인 요금이 청구됩니다.");
}
System.out.println("요금을 청구해주세요");
}
결과값은
연령을 입력해주세요 :
15
비성인 입니다.
비성인 요금이 청구됩니다.
요금을 청구해주세요
으로 콘솔창에 출력된다.
1-3) if - else if문
if - else if문은 조건이 여려개일 경우 사용한다. if - else if문의 형태는 다음과 같다.
if(조건식)
{
//실행할 내용
}
else if(조건식)
{
//실행할 내용
}
else
{
//실행할 내용
}
if문부터 시작하여 조건식이 맞을 때까지 내려가다 최종적으로 모든 조건이 맞지 않으면 else가 실행된다.
public static void main(String[] args)
{
int age;
Scanner input = new Scanner(System.in);//새 스캐너 주소를 input에 넣고
System.out.println("연령을 입력해주세요 : ");
age = input.nextInt();//input안의 nextInt을 불러온다
if(age>19)
{
System.out.println("성인 입니다.");
System.out.println("성인 요금이 청구됩니다.");
}
else if(age>13)
{
System.out.println("청소년 입니다.");
System.out.println("청소년 요금이 청구됩니다.");
}
else if(age>8)
{
System.out.println("어린이 입니다.");
System.out.println("어린이 요금이 청구됩니다.");
}
else
{
System.out.println("유아 입니다.");
System.out.println("유아 요금이 청구됩니다.");
}
System.out.println("요금을 청구해주세요");
}
결과값은
연령을 입력해주세요 :
15
청소년 입니다.
청소년 요금이 청구됩니다.
요금을 청구해주세요
으로 콘솔창에 출력된다.
1-4) 중첩 if문
중첩 if문은 조건에 추가적인 조건이 필요할 때 사용한다. 중첩 if문의 형태는 다음과 같다.
if(조건식1)
{
//실행할 내용
if(조건식2)
{
//실행할 내용
}
}
else
{
//실행할 내용
}
만약 if의 조건식이 false라면 if문 안의 문장의 조건식은 무시되고 else로 바로 진행된다.
public static void main(String[] args) {
String id,pass = null;
Scanner input = new Scanner(System.in);
while(true)
{
System.out.println("ID : ");
id = input.nextLine();
if(id.equals("java"))
{
System.out.println("id Correct");
System.out.println("Enter password");
break;
}
else
{
System.out.println("Wrong id");
}
}
while(true)
{
System.out.println("Password : ");
pass = input.nextLine();
if(pass.equals("1234"))
{
System.out.println("password Correct");
System.out.println("login sucesss");
break;
}
else
{
System.out.println("Wrong password");
}
}
}
while(true)는 반복문으로 미리 적용 시켜 보았다. 지금은 어떤 기능일 지 실행시켜보고 생각만 하고 넘어가자.
while의 역활이 궁금하면 ID PASSWORD를 java 1234와 다르게 적어보자.
결과값은
ID :
java
id Correct
Enter password
Password :
1234
password Correct
login sucesss
으로 콘솔창에 출력된다.
1-5) switch문
switch문은 하나의 조건식으로 여러개의 경우의 수를 처리할 수 있다. case 값이 boolean이 아닌값이 들어간다.
if보다 하위 개념의 조건문이라 if문으로도 switch 기능을 대신할 수 있다. 대신 각각 상황에 맞춰 사용한다면 좀 더 간결한 코드 작성이 가능하다.
switch문 형태는 다음과 같다.
switch(조건식)
{
case 값1
//실행할 내용
break;
case 값2
//실행할 내용
break;
default;
//실행할 내용
}
조건식에 해당되는 값이 각각의 케이스 값과 일치 할 때 해당 케이스의 내용을 실행후 switch 문을 빠져 나온다.
빠져 나올 때 사용 되는것이 break로 알을 깨고(break : 깨다, 부수다) 나온다고 생각하면 된다.
만약 break문이 없다면 조건이 맞아도 아래로 진행되어 결과값이 default까지 모두 출력 될 수 있다.
default는 조건식과 케이스 값이 일치하는 값이 없을 때 실행하고 switch 문을 빠져 나온다. break가 없어도 default는 자체적으로 break 기능을 가진다.
public static void main(String[] args) {
int book = 0;
Scanner input = new Scanner(System.in); //make scanner class(file) and can use scanner funcion
//Scanner input => Scanenr(Data Type) input(Variable), *Variable == Box
System.out.println("<READ BOOK CHECKER>");
System.out.print("Read Book : ");
String tmp = input.nextLine(); // => console get string type data
book = Integer.parseInt(tmp);
//book = address.nextInt() => console get int type data
book = book/10;
switch(book)
{
case 0:
System.out.println("[Bad reader]");
break;
case 1:
System.out.println("[Good reader]");
break;
case 2:
System.out.println("[Nice reader]");
break;
default :
System.out.println("[Awsome reader]");
break;
}
System.out.println("Thank you For using this service");
}
결과값은
<READ BOOK CHECKER>
Read Book : 10
[Good reader]
Thank you For using this service
으로 콘솔창에 출력된다.
위에서 언급한것 처럼 if문은 switch문의 상위 개념이라 if문으로도 위 예제를 만들 수 있다.
직접 만들어 보고 아래와 비교해보길 추천한다.
public static void main(String[] args) {
int book = 0;
System.out.println("<READ BOOK CHECKER>");
System.out.println("- Notice : Over 40 books can't recognize");
System.out.println();
Scanner input = new Scanner(System.in);
while(true)
{
System.out.print("Read Book : ");
String tmp = input.nextLine();
book = Integer.parseInt(tmp);
book = book/10;
if(book == 3)
{
System.out.println("[Awsome reader]");
System.out.println();
}
else if(book == 2)
{
System.out.println("[Nice reader]");
System.out.println();
}
else if(book == 1)
{
System.out.println("[Good reader]");
System.out.println();
}
else if(book == 0)
{
System.out.println("[Bad reader]");
System.out.println();
}
else
{
System.out.println("Over 40 books can't recognize");
break;
}
}
System.out.println("Thank you For using this service");
}
만약 직접 만든 코드의 조건식에 == 이 아닌 비교 연산자(>,<,>=,=<)를 썼다면 이건 switch문의 개념을 정확히 이해 하지 못한것이다.
switch 문은 case를 통해 정확한 한개의 값만 반환하지만, 부등호 연산자는 범위를 나타내는 것이다.
이 의미를 이해하지 못하겠다면, 위 아래 예제를 다시한번 비교해보자.
2) 반복문
반복문은 실행할 내용을 반복적으로 수행하고 싶을 때 사용된다. 그래서 반복문이 조건에 따라 무한히 반복 될 수 있다.
따라서 반복문을 작성할 때, 반복될 조건을 주거나, 무한히 반복되지 않게 조심해서 사용해야 된다.
무한히 반복되는 반복문이면 탈출할 분기점을 만들어 주어 무한반복을 방지한다.
2-1) for문
for 문은 특정 횟수동안 반복하고 싶을 때 사용한다. for문의 구조는 다음과 같다.
for(①초기값;②조건식;④증감식)
{
//③실행되는 내용
}
반복문은 다음과 같은 순서로 실행되고, ①은 1번만 실행된다.
①초기값을 ②조건식에 대입하여 참이면 ③내용을 실행하고 초기값을 ④증감식에 넣어준다.
그 이후 증감식에 넣은 값과 ②의 조건식을 비교하고 참이면 반복한다.
public static void main(String[] args)
{
int sum = 0;
for(int i=1;i<=10;i++)
{
System.out.printf("i=%d sum = %d\n",i,sum+=i);
}
}
결과값은
i=1 sum = 1
i=2 sum = 3
i=3 sum = 6
i=4 sum = 10
i=5 sum = 15
i=6 sum = 21
i=7 sum = 28
i=8 sum = 36
i=9 sum = 45
i=10 sum = 55
으로 콘솔창에 출력된다.
2-2) while문
while문은 조건식에 따라 참이면 반복하고 거짓이면 문장에서 벗어난다. while문의 형태는 다음과 같다.
while(조건식)
{
//실행될 내용
}
앞에서도 언급했듯이 조건식은 boolean값으로 나타낼 수 있는것만 넣어줄 수 있다.
조건식은 질문인데 질문을 하는 이유는 답(예/아니오)을 받기 위해서라고 할 수 있다.
그럼 질문을 하지 않아도 무조건 예라고만 하면 어떻게 될까? while문으로 나타내면 다음과 같다.
while(true)
{
//실행될 내용
}
이렇게 되면 무한 반복이 발생한다. 따라서 실행 될 내용에 탈출 분기점(break 등)을 잘 잡아줘야 된다.
public static void main(String[] args) {
int count = 0;
Scanner sc = new Scanner(System.in);
String answer;
while(true)
{
System.out.printf("Play music? Press (Y/N) : ");
answer = sc.nextLine();
if(answer.equals("Y"))
{
System.out.printf(" - Music played %d time(s)\n",++count);
System.out.println();
}
else if(answer.equals("N"))
{
System.out.println(" - Music stoped - ");
System.out.println();
break;
}
else
{
System.out.println("Wrong input");
System.out.println();
}
}
System.out.println("Thank you For using this service");
}
결과값은
Play music? Press (Y/N) : Y
- Music played 1 time(s)
Play music? Press (Y/N) : Y
- Music played 2 time(s)
Play music? Press (Y/N) : Y
- Music played 3 time(s)
Play music? Press (Y/N) : Y
- Music played 4 time(s)
Play music? Press (Y/N) : Y
- Music played 5 time(s)
Play music? Press (Y/N) : B
Wrong input
Play music? Press (Y/N) : N
- Music stoped -
Thank you For using this service
으로 콘솔창에 출력된다.
2-3) do ~ while문
do ~ while문은 일단 무조건 한번 문장을 수행하고, while 조건식을 검사하여 반복을 결정한다. do ~ while문형태는 다음과 같다.
do
{
//실행될 내용
}while(조건식);
do 안의 내용이 실행되고 실행된 결과가 조건식을 만족하면 반복하고 아니면 탈출한다.
클라이언트에서 서버에 접속할 때 자주 사용된다. 서버가 살아있는지 확인하고 살아있으면 요청을 반복할 수 있다.
3) break, continue문
break문을 만나면 반복을 종료하고 반복문 다음 코드를 실행한다. 현재 상태(반복 등)를 종료한다고 할 수 있다.
continue문은 현재 반복을 해당시점부터 종료하고 다시 해당 반복문을 실행 한다.
두개의 차이를 그림으로 나타내면 다음과 같다
While-------------------------------------------------------------
| ^ | |
| | | |
| | | |
| | | |
| | | |
| | | |
continue V | | V break
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
--------------------------------------------------------|-----------
|
V