Java

[점프 투 자바] 4장 제어문 이해하기

seonggu 2024. 1. 1. 17:19

제어문은 훑고 지나갔다.

몇가지 괜찮은 활용 실습에 관한 코드를 적어보았다.

 

if문에서 contains 메서드 활용

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

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

 

while문 빠져나가기 break

int coffee = 10;
int money = 300;

while (money > 0) {
    System.out.println("돈을 받았으니 커피를 줍니다.");
    coffee--;
    System.out.println("남은 커피의 양은 " + coffee + "입니다.");
    if (coffee == 0) {
        System.out.println("커피가 다 떨어졌습니다. 판매를 중지합니다.");
        break;
    }
}

 

while문으로 돌아가기 continue

int a = 0;
while (a < 10) {
    a++;
    if (a % 2 == 0) {
        continue;  // 짝수인 경우 조건문으로 돌아간다.
    }
    System.out.println(a);  // 홀수만 출력된다.
}

 

for each

for (type 변수명: iterate) {
    body-of-loop
}

iterate는 루프를 돌릴 객체이고 iterate 객체에서 한 개씩 순차적으로 변수명에 대입되어 for문이 수행된다.

iterate에 사용할 수 있는 자료형은 루프를 돌릴 수 있는 자료형 (배열이나 ArrayList 등)만 가능함.