KT DS

[KT DS 보강] 메소드 기초

가은(JANE) 2025. 3. 10. 17:46

메소드 => 함수

  • 함수 ? X -> Y
  • 수학에서 함수 = 해가 있어야 함.

프로그램에서 함수 = 해가 있을 수도 있고 없을 수도 있음.

 

<< 더하기라는 함수 만들기>>

a, b를 받아서

a+b의 결과값 산출

 

더하기(1, 2) = 3

 

// = 는 assignment(할당하는 연산자)
// a+b 결과를 c에 할당해라

static int 더하기(int a, int b){
	int c = a + b;
    return c;
}
public class 계산기{

// 더하기 함수 만들기
	public static int 더하기( int a, int b){
    	int c = a + b;
        return c} // 해를 줘라

// 호출하기
	public static void main(String[] args){
    	int e = 더하기(10, 70);}
}

1. main 함수부터 시작

2. 더하기 호출

3. a자리에 10, b자리에 70

4. 10+70

5. int c = 80이 있다.

6. return c 80을 반환시킨다 (=> 함수를 요청한 애한테 줌)

7. 80이라는 숫자가 더하기로 감

8. 더하기라는 80이라는 숫자를 가짐

9. 80이라는 숫자를 e에 할당

10. e 안에 80이 들어있음.

 

<< 빼서 출력하기>>

빼서 출력하기(a, b, c)

= a-b-c          => 출력

 

빼서 출력하기 (7,6,5)

=> 결과는             -4

public static void 빼서출력하기(int a, int b, int c){
	int e = a - b - c;
    System.out.println(e);
}

<< 더하기와 빼서 출력하기의 차이점>>

  1. void 의 유무
    • void = 반환 타입
    • 반환 타입이 void다 = output이 없다
    • 반환하는 타입이 같아야지 할당 ( 즉, void는 반환값이 X때문에 main에서 부를 수 없음.)
  2. return 의 유무

<< 난수 출력하기>>

난수 출력하기() = R -> 출력 output X

public static void 난수출력하기(){
	System.out.print(Math.random());
}
public static void 난수출력하기(){
	int R = Math.random()*10+1;
    System.out.println(R);
}

<< 둘레 구하기>>

둘레구하기(반지름)

= 2*3.14*r

public static int 둘레구하기(int r){
	int e = 2*r*pi ;
    System.out.println(e) ;
}

 

'KT DS' 카테고리의 다른 글

[KT DS 보강] Primitive와 Reference  (0) 2025.03.17
[KT DS 보강] 메소드 응용  (0) 2025.03.12
[KT DS] Package와 Import와 접근 제어자  (0) 2025.02.06
[KT DS] 클래스  (0) 2025.02.06
[KT DS 25기] 메소드  (1) 2025.02.04