수업

+14 메소드 정리(매개변수)

hs_developer 2022. 5. 20. 09:38
변수
생성자
메소드
객체 지향 3대 요소

1. 캡슐화
2. 상속 / 포함
3. 다형성
접근 지정어
→ public, private, protected, default

옵션
→ static, abstact, final

 

리턴형 : 사용자 요청 처리하는 기능 → 결과 값 보여주는 데이터형

매개변수
: 메소드에서 메소드로 값 전송하는 기능, 사용자 요청 값
: 여러 개 사용 가능 → 3개 이상이면 배열, 클래스 사용 권장
: 클래스는 1개 정보만 담는다.
: new → 메모리 다르게 저장

메소드명 : 식별자

지역 변수
: 메소드 안에서 사용되는 변수, 메소드 안에서만 사용
: 메소드가 종료하면 자동으로 메모리에서 해제

 

 


 

 

매개 변수 입력, 출력 연결 

 

1.

 

정수 입력: 
100
입력 받은 정수 값: 100
static int input()
{
    Scanner sc = new Scanner(System.in);

    System.out.println("정수 입력: ");

    return sc.nextInt();
}


static void output(int a)
{
    System.out.println("입력 받은 정수 값: " + a);
}


static void process()
{
    // input(), output() 연결
    int a = input(); // 메소드 호출 과정
    output(a);

}

public static void main(String[] args) {

    process();
}

 

 

2.

 

실수 입력: 
200
입력 받은 실수 값: 200.0
// 실수 값을 받아서 출력
// 입력 / 출력

/*
 * 1. 입력
 * ㅡㅡ
 * 
 * 2. 출력
 * ㅡㅡ
 */

static double input()
{
    Scanner sc = new Scanner(System.in);

    System.out.println("실수 입력: ");
    return sc.nextDouble();
}

static void output(double d)
{
    System.out.println("입력 받은 실수 값: " + d);
}

// 메소드 조립
static void process()
{
    double d = input();
    output(d);
}


public static void main(String[] args) {

    process();
}

 

 

3. 이름 입력 받아서 출력하는 메소드

 

이름 입력: 
김나나
입력 받은 이름: 김나나
static String input()
{
    Scanner sc = new Scanner(System.in);

    System.out.println("이름 입력: ");

    return sc.next();
}

static void output(String name)
{
    System.out.println("입력 받은 이름: " + name);
}

// 메소드 조립
static void process()
{
    String d = input();
    output(name);
}


public static void main(String[] args) {
    process();
}

 

 

4. 데이터가 여러 개일 때 → 배열, 클래스

 

배열 사용

 

6 7 9 9 4 // 랜덤
static int[] input()
{
    int[] arr = new int[5];
    for(int i=0; i<arr.length; i++)
    {
        arr[i] = (int)(Math.random()*10)+1;
    }
    return arr;

}

// 데이터 여러 개 받는다
static void output(int[] arr)
{
    for(int i:arr)
    {
        System.out.print(i + " ");
    }
}

// 조립
static void process()
{
    int[] arr = input();
    output(arr);
}

public static void main(String[] args) {

    process();
}

 

 

클래스 사용

 

사번 int
이름 String
부서 String
근무지 String
연봉 long
public이 있는 class가 저장 명
public 은 자바 하나에 한 번만 사용 가능

 

=== 사원 정보 ===
사번: 2000
이름: 김다다
부서: 개발부
근무지: 서울
연봉: 3500

 

class Sawon
{
    // 메모리에서 읽기/쓰기
    int sabun;
    String name;
    String dept;
    String loc;
    long pay;
}

public class test {

	static Sawon input()
	{
		// 1. 메모리에 저장 → new
		Sawon s = new Sawon();
		
		Scanner sc = new Scanner(System.in);
		
		System.out.println("사번 입력: ");
		s.sabun = sc.nextInt();
		
		System.out.println("이름 입력: ");
		s.name = sc.next();
		
		System.out.println("부서 입력: ");
		s.dept = sc.next();
		
		System.out.println("근무지 입력: ");
		s.loc = sc.next();
		
		System.out.println("연봉 입력: ");
		s.pay = sc.nextLong();
		
		return s;
	}
	
	static void output(Sawon sa)
	{
		System.out.println("=== 사원 정보 ===");
		System.out.println("사번: " + sa.sabun);
		System.out.println("이름: " + sa.name);
		System.out.println("부서: " + sa.dept);
		System.out.println("근무지: " + sa.loc);
		System.out.println("연봉: " + sa.pay);
		
	}
	
	static void process()
	{
		Sawon s = input();
		output(s);
	}
	
	public static void main(String[] args) {
		process();
	}
	
	
}

 

 

 

5. 

 

입력 / 처리 / 출력

처리 → 세분화

정수 2개 입력 → 최대 값 처리 → 최대 값 받아서 출력

 

첫 번째 정수 입력: 
10
두 번째 정수 입력: 
20
최대 값: 20

 

public class test2 {

    // 입력
    // Scanner 재 사용
    static int input(String msg)
    {
        Scanner sc = new Scanner(System.in);

        System.out.println(msg + " 입력: ");

        return sc.nextInt();

    }

    // 처리
    // 최대 값 넘겨 주는 메소드
    static int max(int a, int b)
    {
        return a<b?b:a;
    }

    // 출력
    static void output(int max)
    {
        System.out.println("최대 값: " + max);
    }

    // 조립
    static void process()
    {
        int a = input("첫 번째 정수");
        int b = input("두 번째 정수");

        // 정수 2개 중에 최대 값은?
        int m = max(a, b);

        output(m);

    }

    public static void main(String[] args) {

        process();
    }

 

 

6. 구구단 출력

 

단 → 입력

구구단 → 만들기, 출력

 

단 입력: 
8
8*1=8
8*2=16
.
.
8*9=72
static String gugudan(int dan)
	{
		String result = "";
		
		for(int i=1; i<=9; i++)
		{
			result += dan + "*" + i + "=" + (dan*i) + "\n";
		}
		return result;
	}

	static void output(String s)
	{
		System.out.println(s);
	}
	
	// 조립
	static void process()
	{
		int dan = test2.input("단");
		
		String gu = gugudan(dan);
		output(gu);
	}
	
	public static void main(String[] args) {
		process();
	}

 

 


 

매개변수 전송

 

Call By Value
: 값 전송
: 복사본 → 원본 그대로 유지

Call By Reference
:

 

===== 변경 전 =====
[0, 0, 0, 0, 0]
===== 변경 후 =====
[59, 57, 30, 3, 24]
public class test {
	
	static void input(int[] arr)
	{
		for(int i=0; i<arr.length; i++)
		{
			arr[i]=(int)(Math.random()*100);
		}
	}

	static void process()
	{
		int[] arr = new int[5];
		
		System.out.println("===== 변경 전 =====");
		System.out.println(Arrays.toString(arr));
		
		System.out.println("===== 변경 후 =====");
		input(arr);
		
		System.out.println(Arrays.toString(arr));
	}
	
	public static void main(String[] args) {
		process();
	}

 

 

다른 메모리에 생성 1 → Call by Value

===== 변경 전 =====
a=10
===== 변경 후 =====
a=10
    static void input2(int a)
    {
        a=100;
    }

    static void process2()
    {
        int a=10;
        System.out.println("===== 변경 전 =====");
        System.out.println("a=" + a);

        System.out.println("===== 변경 후 =====");
        input2(a);

        System.out.println("a=" + a);
    }

    public static void main(String[] args) {
        process2();
    }

 

 

다른 메모리에 생성2

 

===== 변경 전 =====
process: name = 김라라
===== 변경 후 =====
process: name = 김라라
	static void input(String name)
	{
		name = "김다다";
	}
	
	static void process()
	{
		String name = "김라라";
		
		System.out.println("===== 변경 전 =====");
		System.out.println("process: name = " + name);
		
		System.out.println("===== 변경 후 =====");
		input(name);
		System.out.println("process: name = " + name);
	}
	
	public static void main(String[] args) {
		
		process();
	}

 

 

 

같은 메모리에 생성 → Call by Reference

 

h=Human@32d2fa64
===== 변경 전 =====
name=김라라
===== 변경 후 =====
m=Human@32d2fa64
name=김다다
class Human
{
	String name;
}

public class test3 {
	
	static void input2(Human m)
	{
//		System.out.println("m=" + m);
		m.name="김다다";
	}
	
	static void process2()
	{
		Human h = new Human();
		
//		System.out.println("h=" + h);
		h.name = "김라라";
		
		System.out.println("===== 변경 전 =====");
		System.out.println("name=" + h.name);
		
		System.out.println("===== 변경 후 =====");
		input2(h);
		
		System.out.println("name=" + h.name);
	}
    
    public static void main(String[] args) {
		
		process2();
	}
	
}

 

 

Call By Value

: 값 전송
: 메소드 자체에서 변경 (기본형, String)
: 실제는 변경하지 않는다
: 다른 메모리 생성
: 보내는 메모리 != 받는 메모리

Call By Reference

: 주소 전송 
: 주소 안에서 변경 (배열, 클래스)
: 실제도 변경 된다
: 같은 메모리 생성
: 보내는 메모리 == 받는 메모리
: 더 빠름 (메모리를 이미 만들어 놓기 때문에)

 

 

 

 


 

 

// 전역변수
a=10
a=11
a=12
	static int a=10; // 전역변수
	static void increment()
	{		
		System.out.println("a=" + a);
		a++;
	}
	
	public static void main(String[] args) {
		
		increment();
		increment();
		increment();
	}
}

 

 

// 전역변수
a=10
a=10
a=10
static int a=10; // 전역변수
	static void increment()
	{
		// 메모리 생성
		int a=10; // 지역변수(전역변수보다 우선)
		System.out.println("a=" + a);
		a++;
		// 메모리에서 사라진다
	}
	
	public static void main(String[] args) {
		
		increment();
		increment();
		increment();
	}