if 문
if (조건문) {
수행할 문장;
} else {
수행할 문장;
}
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("걸어가라");
}
}
switch/case 문
int num = 2;
String numString = "";
switch (num) { // 입력 변수의 자료형은 byte, short, char, int, enum, String만 가능하다.
case 1: numString = "one";
break;
case 2: numString = "two";
break;
default: numString = "number";
break;
}
System.out.println(numString);
while 문
int treeHit = 0;
while (treeHit < 10) {
treeHit++; // treeHit += 1 로도 표현 가능
System.out.println("나무를 " + treeHit + "번 찍었습니다.");
}
break
강제로 멈춰야 할 때 사용하는 것
int coffee = 10;
int money = 300;
while (money > 0) {
coffee--;
if (coffee == 0) {
System.out.println("커피가 다 떨어졌습니다. 판매를 중지합니다.");
break;
}
}
continue
맨 처음으로 돌아가게 하고 싶은 경우 사용
int a = 0;
while (a < 10) {
a++;
if (a % 2 == 0) {
continue; // 짝수인 경우 조건문으로 돌아간다.
}
System.out.println(a); // 홀수만 출력
}
for 문
for (초기치; 조건문; 증가치) {}
String[] numbers = {"one", "two", "three"};
for(int i=0; i<numbers.length; i++) {
System.out.println(numbers[i]);
}
continue
int[] marks = {90, 25, 67, 45, 80};
for(int i=0; i<marks.length; i++) {
if (marks[i] < 60) {
continue; // 조건문으로 돌아간다.
}
System.out.println((i+1)+"번 학생 축하합니다. 합격입니다.");
}
for each 문
String[] numbers = {"one", "two", "three"};
for(String number: numbers) {
System.out.println(number);
}'Java' 카테고리의 다른 글
| JAVA (2) | 2025.04.07 |
|---|---|
| Java sealed class (0) | 2025.04.04 |
| java Record (0) | 2025.04.04 |
| [Java] 클래스 기본 구조 (4) | 2025.01.16 |
| [Java] Variable(변수), Constant(상수), 자료형 (2) | 2024.08.26 |