[Java] 제어문1 (if/switch/while)

이용준·2022년 10월 26일
0

Java

목록 보기
10/29

1.if 문

if (true){
  System.out.println("A를 실행하자");
}else{
  System.out.println("B를 실행하자");
}

조건이 참이면 if를, 거짓이면 else에 속한 문장을 수행한다.

1-1.연산자

1) and(&&), or(||), not(I)

  • x||y - x와 y 중 적어도 하나가 참이면 참.
  • x&&y - x와 y 모두 참이면, 참.
  • !x - x가 거짓이면 참이다.
 int money = 2000;
 boolean hasCard=true;

 if (money >= 3000 || hasCard){
   System.out.println("택시 타자");
   }else{
     System.out.println("걸어가자");
}

위 예제의 경우 money는 3000보다 작지만 hasCard가 참(||)이므로 "택시 타자"가 출력된다.

2)contains

List 자료형에는 해당 아이템이 있는지 확인하는 contains 메소드가 있다.
(python의 in과 유사한 개념인 듯 하다.)

(조건)만약 돈이 있다면 택시를 타고 없으면 걸어가자.
ArrayList<String> pocket = new ArrayList<String>();
pocket.add("paper");
pocket.add("earphone");
pocket.add("money");

if(pocket.contains("money")){
  System.out.println("택시타고 가자");
}else{
  System.out.println("걸어가자");
 }

pocket 리스트 안에 'money'가 있으므로 if 조건이 참이 되어 "택시타고 가자"가 출력된다.

1-2.else if(다중 조건문)

boolean hasCard = true;
ArrayList<String> pocket = new ArrayList<String>();
pocket.add("paper");
pocket.add("earphone)";

if (pocket.contains("money"){
  System.out.println("택시타고 가자");
}else if(hasCard){
  System.out.println("택시타고 가자");
 }else{
   System.out.println("걸어가자");
 }  

python의 if~elif문과 유사한 방법으로 보인다.

2.Switch/case문

switch/case문은 if문과 비슷하지만 더 정형화된 조건 판단문이다.

public class Sample{
  public static void main(String[] args){
    int month=8;
    String monthString="";
    switch(month){
      case1 : monthString = "Jan";
            break;
      case2 : monthString = "Feb";
      		break;
            ...
      case12 : monthString = "Dec";
      		break;
      deafult: monthString = "Invalid month"'
      		break;
      }
      System.out.println(monthString);
   }
}    

입력값과 일치하는 case 입력값(1,2..)이 있다면 case문에 속한 문장들이 실행되며 break문을 통해 빠져나가게 된다.
만약 입력값에 다른 값이 지정되어 있으면 default:문장이 실행된다.
위처럼 입력값이 정형화도니 경우 if문보다 switch/case문을 사용하는것이 가독성에 좀 더 유리하다.

switch/case문은 if-else 구조로 변경 가능하지만 if-else로 작성된 모든 코드를 switch로 변경할 수는 없다.

3.while문

  • 예제1
"열 번 찍어 안넘어가는 나무 없다."라는 속담을 while문으로 구현해보자.

int treeHit=0;
while(treeHit<10){
  treeHit++;
  System.out.println(String.format("나무를 %s번 찍었습니다.",treeHit));
  if(TreeHit==10){
    System.out.println("나무가 넘어집니다.");
   }
 }  
  • 예제2 (break 사용)
    강제로 while문을 빠져 나가는 break에 대해 알아보도록 하자.
커피 자판기 프로그램 만들기
[조건]
* 돈을 받으면 커피 제공
* 커피가 없으면 "판매중지" 출력
--------------------------
int coffee = 10;
int money = 300;

while(coffe<10){
  System.out.println("커피를 제공한다.");
  coffee--;
  System.out.println(String.format("커피가 %s잔 남았습니다.",%s));
  if (coffee == 0){
    System.out.println(String.format("판매 중지"));
    break;
  }  
}
  • 예제3 (continue)
    조건에 맞지 않는 경우 while문의 맨 처음(조건문)으로 돌아가게 하는 방법에 대해 알아보자.
1부터 10까지 숫자 중 홀수만 출력해보자
------------------------------
int a=0;
while(a<10){
  a++;
  if (a%2==0){
    continue; // 짝수인 경우 조건문으로 돌아간다.
  }
  System.out.println(a);
}  

if문과 while문의 경우 python과 작동 방식이 크게 다르지 않은 것 같다. 반면에 switch/case는 생소해 python에서도 같은 문법이 있었는지 찾아본 결과 python은 swtih문 대신 if-else문을 사용했으며 작동 방식도 유사한 것을 알 수 있었다.

python3.10 부터 match-case 구문이 추가되었다.
해당 구문을 사용한 FizzBuzz 예제는 여기에서 보도록하자.

여기 : 왕초보를 위한 Python: 쉽게 풀어 쓴 기초 문법과 실수

profile
뚝딱뚝딱

0개의 댓글