메서드(4) : 실습, 지역변수

부트캠프(END)/Java|2022. 5. 19. 16:50

지역변수

: 블럭을 기준으로 해당 블럭 내(=메서드 안)에서만 사용될 수 있다.

스택메모리에 저장되며 메서드 호출시에 생성되어 메서드가 끝나면 사라진다.

 

전역변수

: 블럭 상관없이 사용될 수 있다.

static void aaa() {
	int a=10;{
		int b=20;{
			int c=30;
		} //여기부터 c사용할 수 없음
	} //여기부터 b 사용할 수 없음
} //여기부터 a 사용할 수 없음

아래 예시에서 변수 a는 increment() 라는 메서드 안에서만 사용되고 삭제되기 때문에,

increment()를 여러 번 호출하더라도 a 에 a++가 반영되지 않는다.

하지만 b는 전역변수로 선언했기 때문에 b++가 반영된다.

public class VariableEx {
	static void increment () {
		int a = 10; //지역변수(메서드 안)
		System.out.println("a="+a);
		a++; //메모리에서 사라진다.
	}
	public static void main(String[] args) {
		increment(); //a=10
		increment(); //a=10
		increment(); //a=10
	}

	static int b = 10;//전역변수(메서드 밖)
	static void increment2 () {
//		int b = 10; 
// 같은 이름으로 하나의 변수가 지역변수와 전역변수로 둘다 호출되면 지역변수가 우선순위다.
// 굳이 둘 다 하고 싶으면, 전역변수의 경우 VariableEx.b로 명시한다.
		System.out.println("b="+b);
		b++;
	}
	public static void main(String[] args) {
		increment(); //b=10
		increment(); //b=11
		increment(); //b=12
	}
}

 

실습1.  O, X를 10개 입력하고 채점하는 프로그램(지역변수 사용)

package day14;

import java.util.Arrays;
import java.util.Scanner;

public class Methods1 {

    static char[] prob() {
        char[] p = new char[10];
        for (int i = 0; i < p.length; i++) {
            int a = (int)(Math.random() * 2);
            if (a == 1)
                p[i] = 'O';
            if (a == 0)
                p[i] = 'X';
        }
        return p;
    }
    static char[] user() {
        char[] u = new char[10];
        Scanner scan = new Scanner(System.in);
        for (int i = 0; i < u.length; i++) {
            System.out.print((i + 1) + "번째 답 입력(O,X):");
            String s = scan.next();
            char ans = s.charAt(0);
            u[i] = ans;
        }
        return u;
    }

    static int check(char[] p, char[] u) {
        int count = 0;
        for (int i = 0; i < p.length; i++) {
            if (p[i] == u[i])
                count++;
        }
        System.out.printf("\n정답->");
        for (char c: p) {
            System.out.print(c + " ");
        }
        return count;
    }

    public static void main(String[] args) {
        char[] p = prob();
        char[] u = user();
        int score = check(p, u);
        System.out.printf("\n점수:%d점", (score * 10));

    }

}

실습2.  O, X를 10개 입력하고 채점하는 프로그램(전역변수 사용)

package day14;

import java.util.Scanner;

public class Methods2 {
	static char[] p = new char[10];
	static char[] u = new char[10];
	//메서드에서 한 개 이상을 사용시 설정되는 변수! 전역변수!
	
	static void prob() {
		for(int i=0; i<p.length; i++) {
			int q = (int)(Math.random()*2);
			p[i] = (q==0 ? 'O':'X');
		}
	}
	
	static void user() {
		Scanner scan = new Scanner(System.in);
		for(int i=0; i<u.length; i++) {
			System.out.print((i+1)+"번째 답 입력(O,X):");
			char c = scan.next().charAt(0);
			u[i] = c;
		}
	}
	
	static int check() {
		int count = 0;
		for(int i=0; i<p.length; i++) {
			if(p[i]==u[i])
				count++;
		}
		return count;
	}

	public static void main(String[] args) {
		prob();
		user();
		int score = check();
		for(char pp:p)
			System.out.print(pp+" ");
		System.out.println();
		for(char uu:u)
			System.out.print(uu+" ");
		System.out.printf("\n점수:%d",(score*10));
	}

}

실습3. 달력만들기

package day14;
import java.util.Scanner;

public class Methods4 {
    // 사용자 입력 
    static int userInput(String msg) {
        Scanner scan = new Scanner(System.in);
        System.out.print(msg + " 입력:");
        int data = scan.nextInt();
        return data;
    }
    // 요일구하기 
    static int getWeek(int year, int month) {
        // 처리 
        int total = (year - 1) * 365 +
            (year - 1) / 4 -
            (year - 1) / 100 +
            (year - 1) / 400;
        // 2022 -> 5  ==> 2021.12.31
        // 2-2. 전달까지의 총날  수
        int[] lastday = {
            31,
            28,
            31,
            30,
            31,
            30,
            31,
            31,
            30,
            31,
            30,
            31
        };
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) //윤년조건
            lastday[1] = 29;
        else
            lastday[1] = 28;

        for (int i = 0; i < month - 1; i++) {
            total += lastday[i];
        }
        // 2-3. +1 
        total++;
        // ---------------------+  %7 => 요일을 구할 수 있다
        int week = total % 7;
        return week;
    }
    // 출력 
    static void print(int year, int month, int week) {
        int[] lastday = {
            31,
            28,
            31,
            30,
            31,
            30,
            31,
            31,
            30,
            31,
            30,
            31
        };
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) //윤년조건
            lastday[1] = 29;
        else
            lastday[1] = 28;

        System.out.printf("%d년도 %d월\n", year, month);
        String[] strWeek = {
            "일",
            "월",
            "화",
            "수",
            "목",
            "금",
            "토"
        };
        for (String s: strWeek) {
            System.out.print(s + "\t");
        }
        System.out.println("\n");
        for (int i = 1; i <= lastday[month - 1]; i++) {
            if (i == 1) // 맨처음 한번만 수행 (요일까지 공백)
            {
                for (int j = 0; j < week; j++) {
                    System.out.print("\t");
                }
            }
            System.out.printf("%2d\t", i);
            week++;
            if (week > 6) {
                week = 0;
                System.out.println("\n");
            }
        }
    }
    // 조립 
    static void process() {
        int year = userInput("년도");
        int month = userInput("월"); // 반복 제거 
        int week = getWeek(year, month);
        print(year, month, week);

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

}

 

'부트캠프(END) > Java' 카테고리의 다른 글

메서드(5) : call by ***  (0) 2022.05.20
메서드(3) : 실습  (0) 2022.05.18
메서드(2) : 실습  (0) 2022.05.17

댓글()