2025년 2월 27일
if
문 기초if
문을 사용한 단순 조건문if-else
구조else if
문if
문if
문 예제int age = 10;
if (age >= 8) {
System.out.println("학교에 다닙니다.");
} else {
System.out.println("학교에 다니지 않습니다.");
}
Scanner sc = new Scanner(System.in);
System.out.print("정수를 입력하세요: ");
int num = sc.nextInt();
if (num % 3 == 0) {
System.out.printf("%d는 3의 배수입니다.\n", num);
}
sc.close();
Scanner sc = new Scanner(System.in);
System.out.print("두 개의 정수를 입력하세요: ");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
if (n1 >= n2) {
System.out.println("큰 수: " + n1);
} else {
System.out.println("큰 수: " + n2);
}
sc.close();
(방법 1: if
문 비교)
Scanner sc = new Scanner(System.in);
System.out.print("세 개의 정수를 입력하세요: ");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int n3 = sc.nextInt();
int max = n1;
if (max < n2) {
max = n2;
}
if (max < n3) {
max = n3;
}
System.out.println("가장 큰 수: " + max);
sc.close();
(방법 2: else if
활용)
if (n1 >= n2 && n1 >= n3) {
System.out.println("가장 큰 수: " + n1);
} else if (n2 >= n1 && n2 >= n3) {
System.out.println("가장 큰 수: " + n2);
} else {
System.out.println("가장 큰 수: " + n3);
}
Scanner sc = new Scanner(System.in);
System.out.print("세 개의 정수를 입력하세요: ");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int n3 = sc.nextInt();
int sum = n1 + n2 + n3;
double avg = (double) sum / 3;
System.out.printf("합: %d, 평균: %.2f\n", sum, avg);
sc.close();
Scanner sc = new Scanner(System.in);
System.out.print("정수를 입력하세요: ");
int n = sc.nextInt();
if (n % 2 == 0 && n % 3 == 0) {
System.out.printf("%d는 짝수이면서 3의 배수입니다.\n", n);
} else if (n % 2 == 1 && n % 5 == 0) {
System.out.printf("%d는 홀수이면서 5의 배수입니다.\n", n);
}
sc.close();
Scanner sc = new Scanner(System.in);
System.out.print("시험 점수를 입력하세요: ");
int score = sc.nextInt();
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else if (score >= 70) {
System.out.println("C");
} else if (score >= 60) {
System.out.println("D");
} else {
System.out.println("F");
}
sc.close();
Scanner sc = new Scanner(System.in);
System.out.print("나이를 입력하세요: ");
int age = sc.nextInt();
int fare;
if (age < 8) {
fare = 1000;
} else if (age < 14) {
fare = 2000;
} else if (age < 20) {
fare = 2500;
} else {
fare = 3000;
}
System.out.printf("요금은 %d원 입니다.\n", fare);
sc.close();
결과를 변수에 저장하여 코드 단순화
if
블록 내에서 바로 출력하는 대신, 변수를 사용하여 코드 가독성을 높이기중복 코드 최소화
출력 형식 개선
printf("%.2f")
를 활용하여 실수값 출력 시 소수점 자리수 조정switch
문 고려
switch
문을 사용하면 코드가 더 간결해짐if
, if-else
, else if
문법 완벽 이해if
, if-else
, else if
구조 학습