💛 제어문(controlStatement)
: 프로그램의 흐름 (flow)을 바꾸는 역할을 하는 문장
코드 실행 흐름 → 위에서 아래대로 순차적으로 진행 ❌
조건에 따라 문장을 건너뛰거나, 같은 문장 반복수행
제어문 : 조건문과 반복문으로 구성
💛 if문
: (조건식) → True ➡️ {} 괄호 안 문장 수행
if (조건문) {
// 조건식 참(true)일때 수행될 문장
}
조건식 True → 블럭{} 안 문장 수행
조건식 False → if문 다음문장으로 넘어감
class ConditionalStatement1 {
public static void main(String[] args) {
int score = 80;
if (score > 60) {
System.out.println("합격");
}
}
}
class ConditionalStatement2 {
public static void main(String[] args) {
int x = 0;
System.out.printf("x = %d일때, 참인 것은%n", x);
if (x == 0) System.out.println("x == 0");
if (x != 0) System.out.println("x != 0");
if (! (x == 0)) System.out.println("! (x == 0)");
if (! (x != 0)) System.out.println("! (x != 0)");
x = 1;
System.out.printf("x = %d일때, 참인 것은%n", x);
if (x == 0) System.out.println("x == 0");
if (x != 0) System.out.println("x != 0");
if (! (x == 0)) System.out.println("! (x == 0)");
if (! (x != 0)) System.out.println("! (x != 0)");
}
}
💛 블럭(block)
: 괄호{} 사용 → 여러 문장을 하나의 단위로 묶음
블럭 내 문장 → tab
→ 블럭 안에 속한 문장이라는 것 차별화
블럭 내 여러문장, 한문장, no 문장 가능 ✅
한문장 → 블럭 생략 가능
if (조건식) {
// 조건식이 True일때 수행될 문장
} else {
// 조건식 False일때 수행될 문장
}
class ConditionalStatement3 {
public static void main(String[] args) {
System.out.print("숫자를 하나 입력하시오 >>>");
// 사용자입력값 받기 위한 객체생성
Scanner scanner = new Scanner(System.in);
// 사용자입력값 -> int타입으로 변수에저장
int input = scanner.nextInt();
if (input == 0) {
System.out.println("입력하신 숫자는 0입니다.");
} else {
System.out.println("입력하신 숫자는 0이 아닙니다.");
}
}
}
if (조건식①) {
// 조건식① True일때 수행될 문장
} else if (조건식②) {
// 조건식② True일때 수행될 문장
} else if (조건식③) {
// 조건식③ True일때 수행될 문장
} else {
// 위의 조건식 모두 False일때 수행될 문장
else if
→ 여러개 가능
else
→ 생략가능
class ConditionalStatement4 {
public static void main(String[] args) {
int score = 0;
char grade = ' ';
System.out.print("점수를 입력하시오 >>> ");
Scanner scanner = new Scanner(System.in);
score = scanner.nextInt();
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else {
grade = 'D';
}
System.out.println("당신의 학점은 " + grade + "입니다.");
}
}
if (조건식①) {
// 조건식① True일때 수행될 문장
if (조건식②) {
// 조건식①, ② 모두 True일때 수행될 문장
} else {
// 조건식① True, 조건식② False일때 수행될 문장
}
} else {
// 조건식① False일때 수행될 문장
}
class ConditionalStatement5 {
public static void main(String[] args) {
int score = 0;
char grade = ' ', opt = '0';
System.out.print("점수를 입력하시오 >>> ");
Scanner scanner = new Scanner(System.in);
score = scanner.nextInt();
if (score >= 90) {
grade = 'A';
if (score >= 98) {
opt = '+';
} else if (score < 94) {
opt = '-';
}
} else if (score >= 80) {
grade = 'B';
if (score >= 88) {
opt = '+';
} else if (score < 84) {
opt = '-';
}
} else {
grade = 'C';
}
System.out.printf("당신의 학점은 %c%c입니다.%n", grade, opt);
}
}
💛 switch문
: 단 하나의 조건식 → 많은 경우의 수 처리
📎 조건식 먼저 계산 → 결과와 일치하는 case문으로 이동
switch (조건식) {
case 값① :
// 조건식 값① 일때 수행될 문장
break :
case 값② :
// 조건식 값② 일때 수행될 문장
break :
default :
// 조건식 결과와 일치하는 case문이 없을때 수행될 문장
// break 안써도 됨
}
구분 | 제약조건 |
---|---|
switch문 조건식 결과 | 정수, 문자열만 가능 ✅ |
case문 값 | 정수, 상수(문자포함), 문자열 가능 ✅ |
변수, 실수 불가능 ⛔️ | |
중복 불가능 ⛔️ |
class ConditionalStatement6 {
public static void main(String[] args) {
System.out.print("현재 월을 입력하시오 >>> ");
Scanner scanner = new Scanner(System.in);
int month = scanner.nextInt();
switch (month) {
case 3: case 4: case 5:
System.out.println("현재 계절은 봄입니다.");
break;
case 6: case 7: case 8:
System.out.println("현재 계절은 여름입니다.");
break;
case 9: case 10: case 11:
System.out.println("현재 계절은 가을입니다.");
break;
default:
System.out.println("현재 계절은 겨울입니다.");
// default -> break문 생략가능
}
}
}
💛 난수생성 Math.random()
: 0.0 ~ 1.0 사이 double값 하나를 랜덤으로 반환
📎 Math.random() 범위
📍 0.0 <= Math.random() < 1.0
// 0.0 이상, 1.0 미만
📎 Math.random()으로 정수난수 구하기
📍 각 변에 3을 곱한다
0.0 * 3 <= Math.random() * 3 < 1.0 * 3
0.0 <= Math.random() * 3 < 3.0
📍 각 변을 int형으로 반환한다
(int)0.0 <= (int)(Math.random() * 3) < (int)3.0
0 <= (int)(Math.random() * 3) < 3
📍 각 변에 1을 더한다
1 <= (int)(Math.ramdom() * 3) + 1 < 4
📎 Java code
class ConditionalStatement7 {
public static void main(String[] args) {
int num = 0;
for (int i = 1; i <= 5; i++) {
// 1이상 7이하 난수생성 -> 5번 반복
num = (int)(Math.random() * 6) + 1;
System.out.println(num);
}
}
}