# 연습문제 B - 메소드와 조건문
## 04 타입과 형변환
---
1. int와 int의 연산 결과는 int이다.
```
int a = 5 / 2; // 2
```
2. 대입 시, 타입 불일치를 주의해야 한다.
```
String seven = 7; // ERROR
```
3. 타입 변환은 자동변환과 직접변환(캐스팅)이 있다.
```
/* 자동변환 */
double p = 2; // 2 -> 2.0
/* 직접변환 */
System.out.printf("신장: %dcm\n", (int) 176.6);
```
4. 메소드를 통해 문자열을 숫자로 변환할 수 있다.
```
int a = Integer.parseInt("7");
double b = Double.parseDouble("3.14");
```
## 05 메소드
---
#### 메소드 정의
1. 메소드란 일련의 코드를 단순화 하는 문법이다.
2. 메소드는 일반적으로 입력에 따른 결과값을 반환한다.
3. 메소드의 구성요소로는 타입, 이름, 파라미터, 리턴값이 있다.
```
public static TYPE NAME(PARAMETERS) {
return VALUE;
}
```
#### 메소드 호출
1. 메소드를 호출하려면, 먼저 정의돼있어야 한다.
2. 메소드 호출 시, 입력값은 파라미터로 대입된다.
3. 메소드 호출 종료 시, 리턴값은 메소드의 호출 위치로 반환된다.
#### 파라미터
1. 파라미터는 하나도 없거나 그 이상일 수 있다.
```
public static int foo() { ... }
public static int bar(int a) { ... }
public static int somthing(int a, int b) { ... }
```
2. 파라미터의 전달 시 타입 불일치를 주의할 것.
```
/* 메소드 호출 영역 */
int a = square(3.0); // ERROR: double -> int
/* 메소드 정의 영역 */
public static int square(int n) { ... }
```
#### 리턴값
1. 리턴값 반환 시 타입 불일치를 주의할 것.
```
/* 메소드 호출 영역 */
int b = cube(2); // ERROR: int <- double
/* 메소드 정의 영역 */
public static double cube(double n) {
return n * n * n;
}
```
2. 리턴값은 없을 수도 있다. → void 타입 메소드
```
public static void sayHi() {
System.out.println("Hi");
}
```
#### 메소드 호출과 실행 흐름
1. 메소드 내부에서 다른 메소드를 호출할 수 있다.
```
public static void drawRectangle() {
drawLine();
drawEdge();
drawLine();
}
public static void drawLine() {
System.out.println("* * * * * *");
}
public static void drawEdge() {
System.out.println("* *");
}
```
2. 실수 출력 시 소수점 이하의 자리수를 제한할 수 있다.
```
System.out.printf("%.2f", 3.14159265)
```
## 06 조건문
---
#### 조건문이란
1. 조건문이란, 상황에 따라 동작을 달리하는 문법이다.
2. 대표적 조건문으로는 if, if-else, else-if가 있다.
```
if (조건식A) {
...
} else if (조건식B) {
...
} else if (조건식C) {
...
} else {
...
}
```
3. 조건문 내부에 조건문이 중첩될 수 있다.
```
if (isMale) {
if (height >= 173.5) {
...
}
}
```
#### 비교 및 논리 연산자
1. 비교 연산자를 활용하여 다양한 조건식을 만들 수 있다.
```
/* 특정 값보다 큰 경우 */
if (age > 18) { ... }
/* a의 배수 찾기 */
if (num % a == 0) { ... }
```
2. 논리 연산자를 활용하여 풍부한 조건식을 만들 수 있다.
```
/* 동시 조건 확인하기 */
if (조건식A && 조건식B) { ... }
/* AND와 OR 연산자 동시 활용하기 */
if ((sum >= 10.0) && (p >= 4.0 || l >= 4.0 || a >= 4.0)) { ... }
```
## 확인하기
---
<div class="interact_responsive_padding" style="padding:100% 0 0 0;position:relative;margin-bottom:5px;"><div class="interact_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><iframe id="interactApp5cbdad20f0ef010014f30029" width="100%" height="100%" style="border:none;max-width:100%;margin:0;" allowTransparency="true" frameborder="0" src="https://quiz.tryinteract.com/#/5cbdad20f0ef010014f30029/q/1?method=iframe"></iframe></div></div>