본문 바로가기

Java

Java(3) - 제어문(if 조건문), eclipse 실습 코드

728x90
반응형

<목차>

1) 제어문

   1-1) 조건문

   1-2) if 문 유형

2) eclipse 실습 코드

 

 

 

1) 제어문

1-1) 조건문

- 조건에 따라 수행할 문장을 선택할 수 있도록 하여 프로그래밍 순서를 제어

- 조건식에는 boolean형 데이터 타입(true or false)을 결과로 가지는 값, 식이 옴

if (a > 10) {
    System.out.println(“10보다 크다!”);
} else {
    System.out.println(“10보다 작다!”);
}

 

 

1-2) if 문 유형

// 1) if 문
if (조건식) {
    수행할 문장
}

// 2) if-else 문
if (조건식) {
    수행할 문장1
} else {
    수행할 문장2
}

// 3) if-else if-else 문
if (조건식) {
    수행할 문장1
} else if {
    수행할 문장2
} else {
    수행할 문장3
}

 

 

 

2) eclipse 실습 코드

패키지 chapter04.condition

1) IfTest1.class

package chapter04.condition;

public class IfTest1 {

	public static void main(String[] args) {
		// if
		int age = 15;
		
		if (age >= 19) {
			System.out.println("성인입니다.1");
		}
		
		// if-else
		if (age >= 19) {
			System.out.println("성인입니다.2");
		} else {
			System.out.println("어린이입니다.1");
		}
		
		// if-else if-else
		if (age >= 19) {
			System.out.println("성인입니다.3");
		} else if (age > 12) {
			System.out.println("청소년입니다.");
		} else {
			System.out.println("어린이입니다.2");
		}

	}

}

 

 

 

 

2) IfTest2.class

package chapter04.condition;

public class IfTest2 {

	public static void main(String[] args) {
		// if block
		int age = 15;
		
		if (age >= 19) {
			System.out.println("성인입니다.");
			System.out.println("술집 입장.");
		}
		System.out.println("==========");
		
		if (age >= 19)
			System.out.println("성인입니다.");
			System.out.println("술집 입장.");

	}

}

 

 

 

 

3) IfTest3.class

package chapter04.condition;

public class IfTest3 {

	public static void main(String[] args) {
		// if 중첩
		int age = 15;
		boolean man = true;
		
		if (age >= 19) {
			if (man) {
				System.out.println("성인 남성 : 25000원");
			} else {
				System.out.println("성인 여성 : 21000원");
			}
		} else
			System.out.println("청소년 : 15000원");
		
		if (true) {
			System.out.println("값을 넣어도 실행");
		}

	}

}

 

 

 

 

4) If_Example01.class

package chapter04.condition;

import java.util.Scanner;

public class If_Example01 {

	public static void main(String[] args) {
		/*
		 사각형의 넓이 구하기
		 가로, 세로의 길이를 입력받아 넓이를 구하시오.
		 단, 가로와 세로의 길이를 비교하여 정사각형 or 직사각형을 출력한다.
		 
		 출력 결과:
		          가로 입력: 5
		          세로 입력: 4
		          직사각형의 넓이는 20입니다.
		*/
		
		Scanner scan = new Scanner(System.in);
		
		System.out.print("가로 입력: ");
		int width = scan.nextInt(); // 가로
		System.out.print("세로 입력: ");
		int height = scan.nextInt(); // 세로
		
		int area = width * height; // 넓이
		
		if (width <= 0 || height <= 0) {
			System.out.println("잘못 입력함");
		} else if (width == height) {
			System.out.println("정사각형의 넓이는 " + area + "입니다.");
		} else {
			System.out.println("직사각형의 넓이는 " + area + "입니다.");
		}
		
	}

}

 

 

 

 

5) If_Example02.class

package chapter04.condition;

import java.util.Scanner;

public class If_Example02 {

	public static void main(String[] args) {
		/*
		 세 개의 정수를 입력받아,
		 if 문을 활용하여 가장 큰 수를 출력한다.
		 
		 출력결과 :
		          숫자1: 3
		          숫자2: 1
		          숫자3: 2
		          최대값: 3
		*/
		
		Scanner scan = new Scanner(System.in);
		
		System.out.print("숫자1: ");
		int num1 = scan.nextInt();
		System.out.print("숫자2: ");
		int num2 = scan.nextInt();
		System.out.print("숫자3: ");
		int num3 = scan.nextInt();
		
		// 교수님 version
		int maxNum = num1;
		
		if (maxNum < num2) {
			maxNum = num2;
		}
		if (maxNum < num3) {
			maxNum = num3;
		}
		
		System.out.println("최대값: " + maxNum);
		
		/*
		// 내 version
		if (num1 > num2 && num1 > num3) {
			System.out.println("최대값: " + num1);
		} else if (num2 > num1 && num2 > num3) {
			System.out.println("최대값: " + num2);
		} else {
			System.out.println("최대값: " + num3);
		}
		*/

	}

}

 

 

 

 

6) If_Example03.class

package chapter04.condition;

import java.util.Scanner;

public class If_Example03 {

	public static void main(String[] args) {
		/*
		 정수를 1개 입력받고 홀수인지 짝수인지를 출력하라
		 
		 출력결과 : 
		          정수 입력: 4
		          짝수입니다.
		*/
		
		Scanner scan = new Scanner(System.in);
		
		System.out.print("정수 입력: ");
		int num = scan.nextInt();
		
		// 교수님 version
		String result = "짝수";
		
		if (num % 2 != 0) result = "홀수";
		
		System.out.println(result + "입니다.");
		
		
		/*
		// 내 version
		if (num <= 0) {
			System.out.println("숫자를 양의 정수로 다시 입력해주세요.");
		} else if (num % 2 == 0) {
			System.out.println("짝수입니다.");
		} else {
			System.out.println("홀수입니다.");
		}
		*/

	}

}

 

 

 

 

7) If_Example04.class

package chapter04.condition;

import java.util.Scanner;

public class If_Example04 {

	public static void main(String[] args) {
		/*
		 등급 나누기
		 점수(0 ~ 100 사이의 정수)를 입력받아 등급을 출력한다.
		 등급은 수(90 up), 우(80 up), 미(70 up),
		 양(60 up), 가(60 down)로 구분한다.
		 단, 0 ~ 100 이외의 숫자를 입력 시 "잘못 입력했습니다"
		 문구를 출력하고, 프로그램을 종료한다. --> System.exit(0);
		 
		 출력 결과 :
		           점수 입력: 87
		           우
		*/
		
		Scanner scan = new Scanner(System.in);
		System.out.print("점수 입력: ");
		
		int score = scan.nextInt();
		char grade = '수';
		
		if (score < 0 || score > 100) {
			System.out.println("잘못 입력했습니다");
			System.exit(0);
		} else if (score >= 90) {
			grade = '수';
		} else if (score >= 80) {
			grade = '우';
		} else if (score >= 70) {
			grade = '미';
		} else if (score >= 60) {
			grade = '양';
		} else {
			grade = '가';
		}

		System.out.println(grade);

	}

}

 

 

 

 

8) If_Example05.class

package chapter04.condition;

import java.util.GregorianCalendar;
import java.util.Scanner;

public class If_Example05 {

	public static void main(String[] args) {
		/*
		 윤년 구하기
		 연도를 입력받고 입력받은 연도가 평년인지 윤년인지를 출력한다.
		 1. 연수가 4로 나누어 떨어지는 해는 윤년
		 2. 연수가 100으로 나누어 떨어지는 해는 평년
		 3. 연수가 400으로 나누어 떨어지는 해는 윤년
		 
		 연수가 4로 나누어 떨어지면서
		 연수가 100으로는 나누어 떨어지지 않거나
		 연수가 400으로 나누어 떨어지는 해 = 윤년
		 
		 출력 결과 :
		           연도: 2008
		           윤년
		 - 윤년 뜻 : 4년마다 오고 100년마다는 아니지만 400년마다는 윤년이 온다!
		*/
		
		Scanner scan = new Scanner(System.in);
		
		System.out.print("연도: ");
		int year = scan.nextInt();
		String result = "평년";
		
		if (year % 4 == 0
		&& year % 100 != 0
		|| year % 400 == 0) {
			result = "윤년";
		}
		
		System.out.println(result);
		
		// method 사용한 방법
		GregorianCalendar gc = new GregorianCalendar();
		String result2 = 
				gc.isLeapYear(year) ? "윤년" : "평년";
		System.out.println(result2);
		
		/*
		// 내 version
		if (year % 4 == 0) {
			System.out.println("윤년");
		} else if (year % 100 == 0) {
			System.out.println("평년");
		} else if (year % 400 == 0) {
			System.out.println("윤년");
		}
		*/

	}

}

 

 

 

 

9) If_Example06.class

package chapter04.condition;

import java.util.Scanner;

public class If_Example06 {

	public static void main(String[] args) {
		/*
		 BMI 계산하기
		 BMI(체질량 지수)는 몸무게를 키(미터 단위)의 제곱으로 나누어서 계산한다.
		 이 계산 결과에 따라 다음과 같이 판단된다.
		 - 저체중 : 18.5미만
		 - 정상 : 18.5이상 23미만
		 - 과체중 : 23이상 25미만
		 - 비만 : 25이상
		 
		 키(cm), 몸무게를 입력받아 BMI를 계산하시오.
		 출력결과 :
		          BMI 지수: 20.xxxxx(정상)
		*/
		
		Scanner scan = new Scanner(System.in);
		System.out.print("키: ");
		double height = scan.nextDouble();
		System.out.print("몸무게: ");
		double weight = scan.nextDouble();
		
		height /= 100; // 미터 단위로 변환
		
		double bmi = weight / (height * height);
		String result = "";
		
		if (bmi >= 25) {
			result = "비만";
		} else if (bmi >= 23) {
			result = "과체중";
		} else if (bmi >= 18.5) {
			result = "정상";
		} else {
			result = "저체중";
		}
		
		System.out.println("BMI 지수: " + bmi + " (" + result + ")");

	}

}